├── .editorconfig ├── .gitignore ├── .npmrc ├── .travis.yml ├── LICENSE ├── README.md ├── angular.json ├── e2e ├── app.e2e-spec.ts ├── app.po.ts └── tsconfig.e2e.json ├── karma.conf.js ├── ng-package.json ├── package.json ├── protractor.conf.js ├── public_api.ts ├── src ├── app │ ├── app.component.css │ ├── app.component.html │ ├── app.component.spec.ts │ ├── app.component.ts │ ├── app.module.ts │ ├── config.template.ts │ └── modules │ │ └── blob │ │ ├── blob.module.ts │ │ ├── blob.service.spec.ts │ │ ├── blob.service.ts │ │ └── definitions.ts ├── assets │ └── .gitkeep ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── favicon.ico ├── index.html ├── main.ts ├── polyfills.ts ├── styles.css ├── test.ts ├── tsconfig.app.json ├── tsconfig.spec.json └── typings.d.ts ├── tsconfig.json └── tslint.json /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | 8 | # dependencies 9 | /node_modules 10 | 11 | # IDEs and editors 12 | /.idea 13 | .project 14 | .classpath 15 | .c9/ 16 | *.launch 17 | .settings/ 18 | *.sublime-workspace 19 | 20 | # IDE - VSCode 21 | .vscode/* 22 | !.vscode/settings.json 23 | !.vscode/tasks.json 24 | !.vscode/launch.json 25 | !.vscode/extensions.json 26 | 27 | # misc 28 | /.sass-cache 29 | /connect.lock 30 | /coverage 31 | /libpeerconnection.log 32 | npm-debug.log 33 | testem.log 34 | /typings 35 | 36 | # e2e 37 | /e2e/*.js 38 | /e2e/*.map 39 | 40 | # System Files 41 | .DS_Store 42 | Thumbs.db 43 | 44 | src/app/config.ts 45 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "node" 4 | - "9" 5 | cache: 6 | directories: 7 | - "node_modules" 8 | before_install: 9 | - npm install @angular/cli -g 10 | script: 11 | - npm run build 12 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Florent Gros 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://travis-ci.org/Gullfaxi171/angular-azure-blob-service.svg?branch=master)](https://travis-ci.org/Gullfaxi171/angular-azure-blob-service) 2 | 3 | # angular-azure-blob-service 4 | A simple module for communication with Azure Blob Storage from angular apps. Works with @angular 4.3+ 5 | 6 | ## Installation 7 | 8 | ``` 9 | npm install angular-azure-blob-service 10 | ``` 11 | 12 | For older versions of @angular (<4.3) : 13 | ``` 14 | npm install angular-azure-blob-service@0.6.0 15 | ``` 16 | 17 | ## Azure Configuration 18 | 19 | TODO 20 | 21 | ## App Configuration 22 | 23 | In your app.module.ts 24 | 25 | ```js 26 | import { BlobModule } from 'angular-azure-blob-service'; 27 | 28 | @NgModule({ 29 | ... 30 | imports: [ 31 | BlobModule.forRoot() 32 | ], 33 | ... 34 | }) 35 | ``` 36 | 37 | In your component 38 | 39 | ```js 40 | import { BlobService, UploadConfig, UploadParams } from 'angular-azure-blob-service' 41 | ``` 42 | 43 | ```js 44 | const Config: UploadParams = { 45 | sas: 'my sas', 46 | storageAccount: 'my dev storage account', 47 | containerName: 'my container name' 48 | }; 49 | ``` 50 | 51 | Upload the document 52 | 53 | ```js 54 | upload () { 55 | if (this.currentFile !== null) { 56 | const baseUrl = this.blob.generateBlobUrl(Config, this.currentFile.name); 57 | this.config = { 58 | baseUrl: baseUrl, 59 | sasToken: Config.sas, 60 | blockSize: 1024 * 64, // OPTIONAL, default value is 1024 * 32 61 | file: this.currentFile, 62 | complete: () => { 63 | console.log('Transfer completed !'); 64 | }, 65 | error: (err) => { 66 | console.log('Error:', err); 67 | }, 68 | progress: (percent) => { 69 | this.percent = percent; 70 | } 71 | }; 72 | this.blob.upload(this.config); 73 | } 74 | } 75 | ``` 76 | 77 | ## CORS 78 | In order to enable CORS, you should go to your Azure Portal and open the Storage Account. Once there, go to CORS and click "Add" to add a CORS RULE. 79 | 80 | * Allowed origins : your URLs, separated by commas, including ports and http:// or https:// if necessary 81 | * Allowed methods : your choice, you can for instance select all 7 82 | * Allowed headers : x-ms-blob-type,Content-Type,x-ms-blob-content-type,x-ms-meta-target,x-ms-meta-source,x-ms-meta-data* 83 | * Exposed headers : x-ms-meta-* 84 | * Max age : your choice, for instance 200 85 | 86 | you can find more info [here](https://dmrelease.blob.core.windows.net/azurestoragejssample/samples/sample-blob.html) 87 | 88 | Todo : 89 | - write the docs (how to configure cors, how to get the sas token) 90 | - write tests 91 | -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "my-component-library": { 7 | "root": "", 8 | "sourceRoot": "src", 9 | "projectType": "application", 10 | "architect": { 11 | "build": { 12 | "builder": "@angular-devkit/build-angular:browser", 13 | "options": { 14 | "outputPath": "dist", 15 | "index": "src/index.html", 16 | "main": "src/main.ts", 17 | "tsConfig": "src/tsconfig.app.json", 18 | "polyfills": "src/polyfills.ts", 19 | "assets": [ 20 | "src/assets", 21 | "src/favicon.ico" 22 | ], 23 | "styles": [ 24 | "src/styles.css" 25 | ], 26 | "scripts": [] 27 | }, 28 | "configurations": { 29 | "production": { 30 | "optimization": true, 31 | "outputHashing": "all", 32 | "sourceMap": false, 33 | "extractCss": true, 34 | "namedChunks": false, 35 | "aot": true, 36 | "extractLicenses": true, 37 | "vendorChunk": false, 38 | "buildOptimizer": true, 39 | "fileReplacements": [ 40 | { 41 | "replace": "src/environments/environment.ts", 42 | "with": "src/environments/environment.prod.ts" 43 | } 44 | ] 45 | } 46 | } 47 | }, 48 | "serve": { 49 | "builder": "@angular-devkit/build-angular:dev-server", 50 | "options": { 51 | "browserTarget": "my-component-library:build" 52 | }, 53 | "configurations": { 54 | "production": { 55 | "browserTarget": "my-component-library:build:production" 56 | } 57 | } 58 | }, 59 | "extract-i18n": { 60 | "builder": "@angular-devkit/build-angular:extract-i18n", 61 | "options": { 62 | "browserTarget": "my-component-library:build" 63 | } 64 | }, 65 | "test": { 66 | "builder": "@angular-devkit/build-angular:karma", 67 | "options": { 68 | "main": "src/test.ts", 69 | "karmaConfig": "./karma.conf.js", 70 | "polyfills": "src/polyfills.ts", 71 | "tsConfig": "src/tsconfig.spec.json", 72 | "scripts": [], 73 | "styles": [ 74 | "src/styles.css" 75 | ], 76 | "assets": [ 77 | "src/assets", 78 | "src/favicon.ico" 79 | ] 80 | } 81 | }, 82 | "lint": { 83 | "builder": "@angular-devkit/build-angular:tslint", 84 | "options": { 85 | "tsConfig": [ 86 | "src/tsconfig.app.json", 87 | "src/tsconfig.spec.json" 88 | ], 89 | "exclude": [] 90 | } 91 | } 92 | } 93 | }, 94 | "my-component-library-e2e": { 95 | "root": "e2e", 96 | "sourceRoot": "e2e", 97 | "projectType": "application", 98 | "architect": { 99 | "e2e": { 100 | "builder": "@angular-devkit/build-angular:protractor", 101 | "options": { 102 | "protractorConfig": "./protractor.conf.js", 103 | "devServerTarget": "my-component-library:serve" 104 | } 105 | }, 106 | "lint": { 107 | "builder": "@angular-devkit/build-angular:tslint", 108 | "options": { 109 | "tsConfig": [ 110 | "e2e/tsconfig.e2e.json" 111 | ], 112 | "exclude": [] 113 | } 114 | } 115 | } 116 | } 117 | }, 118 | "defaultProject": "my-component-library", 119 | "schematics": { 120 | "@schematics/angular:component": { 121 | "prefix": "app", 122 | "styleext": "css" 123 | }, 124 | "@schematics/angular:directive": { 125 | "prefix": "app" 126 | } 127 | } 128 | } -------------------------------------------------------------------------------- /e2e/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | 3 | describe('my-component-library App', () => { 4 | let page: AppPage; 5 | 6 | beforeEach(() => { 7 | page = new AppPage(); 8 | }); 9 | 10 | it('should display welcome message', () => { 11 | page.navigateTo(); 12 | expect(page.getParagraphText()).toEqual('Welcome to app!'); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /e2e/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo() { 5 | return browser.get('/'); 6 | } 7 | 8 | getParagraphText() { 9 | return element(by.css('app-root h1')).getText(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /e2e/tsconfig.e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/e2e", 5 | "baseUrl": "./", 6 | "module": "commonjs", 7 | "target": "es5", 8 | "types": [ 9 | "jasmine", 10 | "jasminewd2", 11 | "node" 12 | ] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/1.0/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular-devkit/build-angular'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage-istanbul-reporter'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client:{ 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, 'coverage'), reports: [ 'html', 'lcovonly' ], 20 | fixWebpackSourcePaths: true 21 | }, 22 | 23 | reporters: ['progress', 'kjhtml'], 24 | port: 9876, 25 | colors: true, 26 | logLevel: config.LOG_INFO, 27 | autoWatch: true, 28 | browsers: ['Chrome'], 29 | singleRun: false 30 | }); 31 | }; 32 | -------------------------------------------------------------------------------- /ng-package.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/ng-packagr/ng-package.schema.json", 3 | "lib": { 4 | "entryFile": "public_api.ts" 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular-azure-blob-service", 3 | "version": "1.1.0", 4 | "license": "MIT", 5 | "scripts": { 6 | "ng": "ng", 7 | "start": "ng serve", 8 | "build:app": "ng build", 9 | "test": "ng test", 10 | "lint": "ng lint", 11 | "e2e": "ng e2e", 12 | "build": "ng-packagr -p ng-package.json", 13 | "publish": "npm publish dist" 14 | }, 15 | "private": false, 16 | "peerDependencies": { 17 | "@angular/animations": "^6.1.9", 18 | "@angular/common": "^6.1.9", 19 | "@angular/compiler": "^6.1.9", 20 | "@angular/core": "^6.1.9", 21 | "@angular/forms": "^6.1.9", 22 | "@angular/platform-browser": "^6.1.9", 23 | "@angular/platform-browser-dynamic": "^6.1.9", 24 | "@angular/router": "^6.1.9", 25 | "classlist.js": "^1.1.20150312", 26 | "core-js": "^2.5.7", 27 | "node-sass": "^4.9.3", 28 | "rxjs": "^6.3.3", 29 | "web-animations-js": "^2.3.1", 30 | "zone.js": "^0.8.26" 31 | }, 32 | "devDependencies": { 33 | "@angular-devkit/build-angular": "~0.8.0", 34 | "@angular/cli": "6.2.3", 35 | "@angular/compiler-cli": "^6.1.9", 36 | "@angular/language-service": "^6.1.9", 37 | "@types/jasmine": "~2.8.8", 38 | "@types/jasminewd2": "~2.0.4", 39 | "@types/node": "~10.11.3", 40 | "codelyzer": "~4.4.4", 41 | "jasmine-core": "~3.2.1", 42 | "jasmine-spec-reporter": "~4.2.1", 43 | "karma": "~3.0.0", 44 | "karma-chrome-launcher": "~2.2.0", 45 | "karma-cli": "~1.0.1", 46 | "karma-coverage-istanbul-reporter": "^2.0.4", 47 | "karma-jasmine": "~1.1.2", 48 | "karma-jasmine-html-reporter": "^1.3.1", 49 | "ng-packagr": "^4.2.0", 50 | "protractor": "~5.4.1", 51 | "ts-node": "~7.0.1", 52 | "tslint": "~5.11.0", 53 | "typescript": "^2.9.2" 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /protractor.conf.js: -------------------------------------------------------------------------------- 1 | // Protractor configuration file, see link for more information 2 | // https://github.com/angular/protractor/blob/master/lib/config.ts 3 | 4 | const { SpecReporter } = require('jasmine-spec-reporter'); 5 | 6 | exports.config = { 7 | allScriptsTimeout: 11000, 8 | specs: [ 9 | './e2e/**/*.e2e-spec.ts' 10 | ], 11 | capabilities: { 12 | 'browserName': 'chrome' 13 | }, 14 | directConnect: true, 15 | baseUrl: 'http://localhost:4200/', 16 | framework: 'jasmine', 17 | jasmineNodeOpts: { 18 | showColors: true, 19 | defaultTimeoutInterval: 30000, 20 | print: function() {} 21 | }, 22 | onPrepare() { 23 | require('ts-node').register({ 24 | project: 'e2e/tsconfig.e2e.json' 25 | }); 26 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /public_api.ts: -------------------------------------------------------------------------------- 1 | export * from './src/app/modules/blob/blob.module' 2 | -------------------------------------------------------------------------------- /src/app/app.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Gullfaxi171/angular-azure-blob-service/2d9bfe865317e34647085da9fcae7997d35e60b0/src/app/app.component.css -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 |

Angular Azure Blob Storage

2 | 3 | 4 |

Progress: {{ percent }}%

5 | -------------------------------------------------------------------------------- /src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, async } from '@angular/core/testing' 2 | import { AppComponent } from './app.component' 3 | 4 | import { BlobModule } from './modules/blob/blob.module' 5 | 6 | describe('AppComponent', () => { 7 | beforeEach(async(() => { 8 | TestBed.configureTestingModule({ 9 | imports: [BlobModule.forRoot()], 10 | declarations: [ 11 | AppComponent 12 | ], 13 | }).compileComponents() 14 | })) 15 | it('should create the app', async(() => { 16 | const fixture = TestBed.createComponent(AppComponent) 17 | const app = fixture.debugElement.componentInstance 18 | expect(app).toBeTruthy() 19 | })) 20 | }) 21 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core' 2 | import { BlobService, UploadConfig } from './modules/blob/blob.module' 3 | import { Config } from './config' 4 | 5 | @Component({ 6 | selector: 'app-root', 7 | templateUrl: './app.component.html', 8 | styleUrls: ['./app.component.css'] 9 | }) 10 | export class AppComponent { 11 | /** The upload config */ 12 | config: UploadConfig 13 | /** The selected file */ 14 | currentFile: File 15 | /** The current percent to be displayed */ 16 | percent: number 17 | constructor (private blob: BlobService) { 18 | this.currentFile = null 19 | this.config = null 20 | this.percent = 0 21 | } 22 | updateFiles (files) { 23 | this.currentFile = files[0] 24 | } 25 | upload () { 26 | if (this.currentFile !== null) { 27 | const baseUrl = this.blob.generateBlobUrl(Config, this.currentFile.name) 28 | this.config = { 29 | baseUrl: baseUrl, 30 | blockSize: 1024 * 32, 31 | sasToken: Config.sas, 32 | file: this.currentFile, 33 | complete: () => { 34 | console.log('Transfer completed !') 35 | }, 36 | error: (err) => { 37 | console.log('Error:', err) 38 | }, 39 | progress: (percent) => { 40 | this.percent = percent 41 | } 42 | } 43 | this.blob.upload(this.config) 44 | } 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser' 2 | import { NgModule } from '@angular/core' 3 | 4 | import { AppComponent } from './app.component' 5 | import { BlobModule } from './modules/blob/blob.module' 6 | import { FormsModule } from '@angular/forms' 7 | 8 | @NgModule({ 9 | declarations: [ 10 | AppComponent 11 | ], 12 | imports: [ 13 | BrowserModule, 14 | FormsModule, 15 | BlobModule.forRoot() 16 | ], 17 | providers: [], 18 | bootstrap: [AppComponent] 19 | }) 20 | export class AppModule { } 21 | -------------------------------------------------------------------------------- /src/app/config.template.ts: -------------------------------------------------------------------------------- 1 | import { UploadParams } from './modules/blob/blob.module' 2 | 3 | export const Config: UploadParams = { 4 | sas: 'my sas', 5 | storageAccount: 'my dev storage account', 6 | containerName: 'my container name' 7 | } 8 | -------------------------------------------------------------------------------- /src/app/modules/blob/blob.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule, ModuleWithProviders } from '@angular/core' 2 | import { CommonModule } from '@angular/common' 3 | import { HttpClientModule } from '@angular/common/http' 4 | 5 | import { BlobService } from './blob.service' 6 | export { BlobService } from './blob.service' 7 | export { UploadConfig, UploadParams } from './definitions' 8 | 9 | @NgModule({ 10 | imports: [ 11 | CommonModule, 12 | HttpClientModule 13 | ], 14 | declarations: [], 15 | exports: [] 16 | }) 17 | export class BlobModule { 18 | static forRoot(): ModuleWithProviders { 19 | return { 20 | ngModule: BlobModule, 21 | providers: [ 22 | BlobService 23 | ] 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/app/modules/blob/blob.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, inject } from '@angular/core/testing' 2 | 3 | import { BlobService } from './blob.service' 4 | import { HttpClientModule } from '@angular/common/http' 5 | 6 | describe('BlobService', () => { 7 | beforeEach(() => { 8 | TestBed.configureTestingModule({ 9 | imports: [HttpClientModule], 10 | providers: [BlobService] 11 | }) 12 | }) 13 | 14 | it('should be created', inject([BlobService], (service: BlobService) => { 15 | expect(service).toBeTruthy() 16 | })) 17 | }) 18 | -------------------------------------------------------------------------------- /src/app/modules/blob/blob.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core' 2 | import { HttpClient, HttpHeaders } from '@angular/common/http' 3 | import { UploadParams, UploadConfig } from './definitions' 4 | @Injectable() 5 | export class BlobService { 6 | static DefaultBlockSize = 1024 * 32 7 | constructor (private http: HttpClient) { } 8 | generateBlobUrl ( 9 | params: UploadParams, 10 | filename: string, 11 | useAzureStorageEmulator = false, 12 | azureStorageEmulatorBaseUrl = '') { 13 | const url = useAzureStorageEmulator ? azureStorageEmulatorBaseUrl : `https://${params.storageAccount}.blob.core.windows.net` 14 | return `${url}/${params.containerName}/${filename}` 15 | } 16 | private uploadFileInBlocks (reader, state) { 17 | if (!state.cancelled) { 18 | if (state.totalBytesRemaining > 0) { 19 | const fileContent = state.file.slice(state.currentFilePointer, state.currentFilePointer + state.maxBlockSize) 20 | const blockId = state.blockIdPrefix + this.prependZeros(state.blockIds.length, 6) 21 | state.blockIds.push(btoa(blockId)) 22 | reader.readAsArrayBuffer(fileContent) 23 | state.currentFilePointer += state.maxBlockSize 24 | state.totalBytesRemaining -= state.maxBlockSize 25 | if (state.totalBytesRemaining < state.maxBlockSize) { 26 | state.maxBlockSize = state.totalBytesRemaining 27 | } 28 | } else { 29 | this.commitBlockList(state) 30 | } 31 | } 32 | } 33 | private commitBlockList (state) { 34 | const uri = state.fileUrl + '&comp=blocklist' 35 | const headers = new HttpHeaders({ 'x-ms-blob-content-type': state.file.type }) 36 | let requestBody = '' 37 | for (let i = 0; i < state.blockIds.length; i++) { 38 | requestBody += '' + state.blockIds[i] + '' 39 | } 40 | requestBody += '' 41 | 42 | this.http.put(uri, requestBody, { headers: headers, responseType: 'text' }) 43 | .subscribe(_elem => { 44 | if (state.complete) { 45 | state.complete() 46 | } 47 | }, err => { 48 | console.log({ error: err }) 49 | if (state.error) { 50 | state.error(err) 51 | } 52 | }) 53 | } 54 | private initializeState (config: UploadConfig) { 55 | let blockSize = BlobService.DefaultBlockSize 56 | if (config.blockSize) { 57 | blockSize = config.blockSize 58 | } 59 | let maxBlockSize = blockSize 60 | let numberOfBlocks = 1 61 | const file = config.file 62 | const fileSize = file.size 63 | if (fileSize < blockSize) { 64 | maxBlockSize = fileSize 65 | } 66 | if (fileSize % maxBlockSize === 0) { 67 | numberOfBlocks = fileSize / maxBlockSize 68 | } else { 69 | numberOfBlocks = fileSize / maxBlockSize + 1 70 | } 71 | 72 | return { 73 | maxBlockSize: maxBlockSize, // Each file will be split in 256 KB. 74 | numberOfBlocks: numberOfBlocks, 75 | totalBytesRemaining: fileSize, 76 | currentFilePointer: 0, 77 | blockIds: new Array(), 78 | blockIdPrefix: 'block-', 79 | bytesUploaded: 0, 80 | submitUri: null, 81 | file: file, 82 | baseUrl: config.baseUrl, 83 | sasToken: config.sasToken, 84 | fileUrl: config.baseUrl + config.sasToken, 85 | progress: config.progress, 86 | complete: config.complete, 87 | error: config.error, 88 | cancelled: false 89 | } 90 | } 91 | upload (config: UploadConfig) { 92 | const state = this.initializeState(config) 93 | const reader = new FileReader() 94 | reader.onloadend = (evt: any) => { 95 | if (evt.target.readyState === 2 && !state.cancelled) { 96 | const uri = state.fileUrl + '&comp=block&blockid=' + state.blockIds[state.blockIds.length - 1] 97 | const requestData = evt.target.result 98 | const requestData2 = new Uint8Array(evt.target.result) 99 | const headers = new HttpHeaders({ 'x-ms-blob-type': 'BlockBlob', 'Content-Type': 'application/octet-stream' }) 100 | this.http.put(uri, requestData, { headers: headers, responseType: 'text' }) 101 | .subscribe(_elem => { 102 | state.bytesUploaded += requestData2.length 103 | const percentComplete = Math.round((state.bytesUploaded / state.file.size) * 1000) / 10 104 | if (state.progress) { 105 | state.progress(percentComplete) 106 | } 107 | 108 | this.uploadFileInBlocks(reader, state) 109 | }, err => { 110 | console.log({ error: err }) 111 | if (state.error) { 112 | state.error(err) 113 | } 114 | }) 115 | } 116 | } 117 | 118 | this.uploadFileInBlocks(reader, state) 119 | 120 | return { 121 | cancel: () => { 122 | state.cancelled = true 123 | } 124 | } 125 | } 126 | private prependZeros (number, length) { 127 | let str = '' + number 128 | while (str.length < length) { 129 | str = '0' + str 130 | } 131 | return str 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/app/modules/blob/definitions.ts: -------------------------------------------------------------------------------- 1 | import { HttpErrorResponse } from '@angular/common/http' 2 | 3 | export interface UploadParams { 4 | /** The SAS, that can be found in the storage account parameters */ 5 | sas: string 6 | /** The name of the storage account ressource */ 7 | storageAccount: string 8 | /** The name of the container */ 9 | containerName: string 10 | } 11 | 12 | export interface UploadConfig { 13 | /** SAS Token */ 14 | sasToken: string 15 | /** Base URL of the container */ 16 | baseUrl: string 17 | /** The file that needs to be uploaded */ 18 | file: File 19 | /** Blocksize (default 1024*32) */ 20 | blockSize?: number 21 | /** Event triggered on complete */ 22 | complete?: () => void 23 | /** Event triggered en error */ 24 | error?: (err: HttpErrorResponse) => void 25 | /** Event fired on each progress update */ 26 | progress?: (percent: number) => void 27 | } 28 | -------------------------------------------------------------------------------- /src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Gullfaxi171/angular-azure-blob-service/2d9bfe865317e34647085da9fcae7997d35e60b0/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // The file contents for the current environment will overwrite these during build. 2 | // The build system defaults to the dev environment which uses `environment.ts`, but if you do 3 | // `ng build --env=prod` then `environment.prod.ts` will be used instead. 4 | // The list of which env maps to which file can be found in `.angular-cli.json`. 5 | 6 | export const environment = { 7 | production: false 8 | }; 9 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Gullfaxi171/angular-azure-blob-service/2d9bfe865317e34647085da9fcae7997d35e60b0/src/favicon.ico -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | MyComponentLibrary 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core' 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic' 3 | 4 | import { AppModule } from './app/app.module' 5 | import { environment } from './environments/environment' 6 | 7 | if (environment.production) { 8 | enableProdMode() 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule) 12 | .catch(err => console.log(err)) 13 | -------------------------------------------------------------------------------- /src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE9, IE10 and IE11 requires all of the following polyfills. **/ 22 | import 'core-js/es6/symbol' 23 | import 'core-js/es6/object' 24 | import 'core-js/es6/function' 25 | import 'core-js/es6/parse-int' 26 | import 'core-js/es6/parse-float' 27 | import 'core-js/es6/number' 28 | import 'core-js/es6/math' 29 | import 'core-js/es6/string' 30 | import 'core-js/es6/date' 31 | import 'core-js/es6/array' 32 | import 'core-js/es6/regexp' 33 | import 'core-js/es6/map' 34 | import 'core-js/es6/weak-map' 35 | import 'core-js/es6/set' 36 | 37 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 38 | import 'classlist.js' // Run `npm install --save classlist.js`. 39 | 40 | /** IE10 and IE11 requires the following for the Reflect API. */ 41 | import 'core-js/es6/reflect' 42 | 43 | 44 | /** Evergreen browsers require these. **/ 45 | // Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove. 46 | import 'core-js/es7/reflect' 47 | 48 | 49 | /** 50 | * Required to support Web Animations `@angular/platform-browser/animations`. 51 | * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation 52 | **/ 53 | import 'web-animations-js' // Run `npm install --save web-animations-js`. 54 | 55 | /** 56 | * By default, zone.js will patch all possible macroTask and DomEvents 57 | * user can disable parts of macroTask/DomEvents patch by setting following flags 58 | */ 59 | 60 | // (window as any).__Zone_disable_requestAnimationFrame = true // disable patch requestAnimationFrame 61 | // (window as any).__Zone_disable_on_property = true // disable patch onProperty such as onclick 62 | // (window as any).__zone_symbol__BLACK_LISTED_EVENTS = ['scroll', 'mousemove'] // disable patch specified eventNames 63 | 64 | /* 65 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 66 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 67 | */ 68 | // (window as any).__Zone_enable_cross_context_check = true 69 | 70 | /*************************************************************************************************** 71 | * Zone JS is required by default for Angular itself. 72 | */ 73 | import 'zone.js/dist/zone' // Included with Angular CLI. 74 | 75 | 76 | 77 | /*************************************************************************************************** 78 | * APPLICATION IMPORTS 79 | */ 80 | -------------------------------------------------------------------------------- /src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | -------------------------------------------------------------------------------- /src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/dist/long-stack-trace-zone' 4 | import 'zone.js/dist/proxy.js' 5 | import 'zone.js/dist/sync-test' 6 | import 'zone.js/dist/jasmine-patch' 7 | import 'zone.js/dist/async-test' 8 | import 'zone.js/dist/fake-async-test' 9 | import { getTestBed } from '@angular/core/testing' 10 | import { 11 | BrowserDynamicTestingModule, 12 | platformBrowserDynamicTesting 13 | } from '@angular/platform-browser-dynamic/testing' 14 | 15 | // Unfortunately there's no typing for the `__karma__` variable. Just declare it as any. 16 | declare const __karma__: any 17 | declare const require: any 18 | 19 | // Prevent Karma from running prematurely. 20 | __karma__.loaded = function () {} 21 | 22 | // First, initialize the Angular testing environment. 23 | getTestBed().initTestEnvironment( 24 | BrowserDynamicTestingModule, 25 | platformBrowserDynamicTesting() 26 | ) 27 | // Then we find all the tests. 28 | const context = require.context('./', true, /\.spec\.ts$/) 29 | // And load the modules. 30 | context.keys().map(context) 31 | // Finally, start Karma to run the tests. 32 | __karma__.start() 33 | -------------------------------------------------------------------------------- /src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "baseUrl": "./", 6 | "module": "es2015", 7 | "types": [] 8 | }, 9 | "exclude": [ 10 | "test.ts", 11 | "**/*.spec.ts" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "baseUrl": "./", 6 | "module": "commonjs", 7 | "target": "es5", 8 | "types": [ 9 | "jasmine", 10 | "node" 11 | ] 12 | }, 13 | "files": [ 14 | "test.ts", 15 | "polyfills.ts" 16 | ], 17 | "include": [ 18 | "**/*.spec.ts", 19 | "**/*.d.ts" 20 | ] 21 | } 22 | -------------------------------------------------------------------------------- /src/typings.d.ts: -------------------------------------------------------------------------------- 1 | /* SystemJS module definition */ 2 | declare var module: NodeModule 3 | interface NodeModule { 4 | id: string 5 | } 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "outDir": "./dist/out-tsc", 5 | "sourceMap": true, 6 | "declaration": false, 7 | "moduleResolution": "node", 8 | "emitDecoratorMetadata": true, 9 | "experimentalDecorators": true, 10 | "target": "es5", 11 | "typeRoots": [ 12 | "node_modules/@types" 13 | ], 14 | "lib": [ 15 | "es2017", 16 | "dom" 17 | ], 18 | "module": "es2015", 19 | "baseUrl": "./" 20 | } 21 | } -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rulesDirectory": [ 3 | "node_modules/codelyzer" 4 | ], 5 | "rules": { 6 | "arrow-return-shorthand": true, 7 | "callable-types": true, 8 | "class-name": true, 9 | "comment-format": [ 10 | true, 11 | "check-space" 12 | ], 13 | "curly": true, 14 | "eofline": true, 15 | "forin": true, 16 | "import-blacklist": [ 17 | true 18 | ], 19 | "import-spacing": true, 20 | "indent": [ 21 | true, 22 | "spaces" 23 | ], 24 | "interface-over-type-literal": true, 25 | "label-position": true, 26 | "max-line-length": [ 27 | true, 28 | 140 29 | ], 30 | "member-access": false, 31 | "member-ordering": [ 32 | true, 33 | { 34 | "order": [ 35 | "static-field", 36 | "instance-field", 37 | "static-method", 38 | "instance-method" 39 | ] 40 | } 41 | ], 42 | "no-arg": true, 43 | "no-bitwise": true, 44 | "no-console": [ 45 | true, 46 | "debug", 47 | "info", 48 | "time", 49 | "timeEnd", 50 | "trace" 51 | ], 52 | "no-construct": true, 53 | "no-debugger": true, 54 | "no-duplicate-super": true, 55 | "no-empty": false, 56 | "no-empty-interface": true, 57 | "no-eval": true, 58 | "no-inferrable-types": [ 59 | true, 60 | "ignore-params" 61 | ], 62 | "no-misused-new": true, 63 | "no-non-null-assertion": true, 64 | "no-shadowed-variable": true, 65 | "no-string-literal": false, 66 | "no-string-throw": true, 67 | "no-switch-case-fall-through": true, 68 | "no-trailing-whitespace": true, 69 | "no-unnecessary-initializer": true, 70 | "no-unused-expression": true, 71 | "no-use-before-declare": true, 72 | "no-var-keyword": true, 73 | "object-literal-sort-keys": false, 74 | "one-line": [ 75 | true, 76 | "check-open-brace", 77 | "check-catch", 78 | "check-else", 79 | "check-whitespace" 80 | ], 81 | "prefer-const": true, 82 | "quotemark": [ 83 | true, 84 | "single" 85 | ], 86 | "radix": true, 87 | "semicolon": [ 88 | true, 89 | "never" 90 | ], 91 | "triple-equals": [ 92 | true, 93 | "allow-null-check" 94 | ], 95 | "typedef-whitespace": [ 96 | true, 97 | { 98 | "call-signature": "nospace", 99 | "index-signature": "nospace", 100 | "parameter": "nospace", 101 | "property-declaration": "nospace", 102 | "variable-declaration": "nospace" 103 | } 104 | ], 105 | "typeof-compare": true, 106 | "unified-signatures": true, 107 | "variable-name": false, 108 | "whitespace": [ 109 | true, 110 | "check-branch", 111 | "check-decl", 112 | "check-operator", 113 | "check-separator", 114 | "check-type" 115 | ], 116 | "directive-selector": [ 117 | true, 118 | "attribute", 119 | "app", 120 | "camelCase" 121 | ], 122 | "component-selector": [ 123 | true, 124 | "element", 125 | "app", 126 | "kebab-case" 127 | ], 128 | "use-input-property-decorator": true, 129 | "use-output-property-decorator": true, 130 | "use-host-property-decorator": true, 131 | "no-input-rename": true, 132 | "no-output-rename": true, 133 | "use-life-cycle-interface": true, 134 | "use-pipe-transform-interface": true, 135 | "component-class-suffix": true, 136 | "directive-class-suffix": true, 137 | "no-access-missing-member": true, 138 | "templates-use-public": true, 139 | "invoke-injectable": true 140 | } 141 | } 142 | --------------------------------------------------------------------------------