admin管理员组文章数量:1279234
I'm trying to figure out how to upload an image using ngx-awesome-uploader to azure storage blob from Angular.
I'd like to be able to send it directly to azure storage blob from angular using this library. I've been able to send it to my nodejs backend no problem, but it's been challenging for me to send it directly to blob storage instead. Can anyone provide a working example of how to do this? I appreciate any help!
Choose Simple Demo in stackblitz. Not Advanced Demo
Stackblitz example of ngx awesome uploader
The file is passed to this. (Console output below code)
import { FilePreviewModel } from 'ngx-awesome-uploader';
import { HttpRequest, HttpClient, HttpEvent, HttpEventType } from '@angular/mon/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { FilePickerAdapter } from 'ngx-awesome-uploader';
export class DemoFilePickerAdapter extends FilePickerAdapter {
constructor(private http: HttpClient) {
super();
}
public uploadFile(fileItem: FilePreviewModel) {
const form = new FormData();
form.append('file', fileItem.file);
console.log("FILE OUTPUT");
console.log(fileItem.file);
//need to replace everything below with code to add to storage blob
const api = '';
const req = new HttpRequest('POST', api, form, {reportProgress: true});
return this.http.request(req)
.pipe(
map( (res: HttpEvent<any>) => {
if (res.type === HttpEventType.Response) {
return res.body.id.toString();
} else if (res.type === HttpEventType.UploadProgress) {
// Compute and show the % done:
const UploadProgress = +Math.round((100 * res.loaded) / res.total);
return UploadProgress;
}
})
);
}
}
the console.output of FILE OUTPUT is
I'm trying to figure out how to upload an image using ngx-awesome-uploader to azure storage blob from Angular.
I'd like to be able to send it directly to azure storage blob from angular using this library. I've been able to send it to my nodejs backend no problem, but it's been challenging for me to send it directly to blob storage instead. Can anyone provide a working example of how to do this? I appreciate any help!
Choose Simple Demo in stackblitz. Not Advanced Demo
Stackblitz example of ngx awesome uploader
The file is passed to this. (Console output below code)
import { FilePreviewModel } from 'ngx-awesome-uploader';
import { HttpRequest, HttpClient, HttpEvent, HttpEventType } from '@angular/mon/http';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { FilePickerAdapter } from 'ngx-awesome-uploader';
export class DemoFilePickerAdapter extends FilePickerAdapter {
constructor(private http: HttpClient) {
super();
}
public uploadFile(fileItem: FilePreviewModel) {
const form = new FormData();
form.append('file', fileItem.file);
console.log("FILE OUTPUT");
console.log(fileItem.file);
//need to replace everything below with code to add to storage blob
const api = 'https://demo-file-uploader.free.beeceptor.';
const req = new HttpRequest('POST', api, form, {reportProgress: true});
return this.http.request(req)
.pipe(
map( (res: HttpEvent<any>) => {
if (res.type === HttpEventType.Response) {
return res.body.id.toString();
} else if (res.type === HttpEventType.UploadProgress) {
// Compute and show the % done:
const UploadProgress = +Math.round((100 * res.loaded) / res.total);
return UploadProgress;
}
})
);
}
}
the console.output of FILE OUTPUT is
Share Improve this question edited Mar 4, 2020 at 22:52 user6680 asked Mar 4, 2020 at 19:24 user6680user6680 1397 gold badges41 silver badges96 bronze badges 4- learn.microsoft./en-us/azure/storage/blobs/… – peinearydevelopment Commented Mar 4, 2020 at 19:44
- This code snippet is confusing to me. Can you show me an example with the stackblitz I linked? – user6680 Commented Mar 4, 2020 at 19:54
- @user6680 - please edit your question to contain any/all relevant code, rather than asking people to click through to a link. Links-to-code are discouraged, since links can rot/die/disappear, then future readers have no reference. It's important to include all specifics in your question, including the area in which you're having the problem, errors, expected vs actual oute, etc. – David Makogon Commented Mar 4, 2020 at 22:18
- Sorry about that. I added additional information to my question – user6680 Commented Mar 4, 2020 at 22:42
1 Answer
Reset to default 11 +150According to my test, if you want to upload file to Azure blob, please refer to the following steps
- install Azure storage SDk
npm install @azure/storage-blob
- Update app.ponent.html File
<div class="form-group">
<label for="file">Choose File</label>
<input type="file"
id="file"
(change)="onFileChange($event)">
</div>
- Update Environment.ts
export const environment = {
production: false,
accountName : "<account name>",
containerName:"",
key:""
};
- Add the following code in polyfills.ts
(window as any).global = window;
(window as any).process = require( 'process' );
(window as any).Buffer = require( 'buffer' ).Buffer;
- Add the following code in app.ponent.ts
import { Component } from '@angular/core';
import {BlobServiceClient,AnonymousCredential,newPipeline } from '@azure/storage-blob';
import { environment } from './../environments/environment';
@Component({
selector: 'app-root',
templateUrl: './app.ponent.html',
styleUrls: ['./app.ponent.css']
})
export class AppComponent {
title = 'web1';
currentFile : File =null;
onFileChange(event) {
this.currentFile = event.target.files[0];
console.log(this.currentFile.name)
console.log(this.currentFile.type)
// generate account sas token
const accountName =environment.accountName;
const key=environment.key;
const start = new Date(new Date().getTime() - (15 * 60 * 1000));
const end = new Date(new Date().getTime() + (30 * 60 * 1000));
const signedpermissions = 'rwdlac';
const signedservice = 'b';
const signedresourcetype = 'sco';
const signedexpiry = end.toISOString().substring(0, end.toISOString().lastIndexOf('.')) + 'Z';
const signedProtocol = 'https';
const signedversion = '2018-03-28';
const StringToSign =
accountName+ '\n' +
signedpermissions + '\n' +
signedservice + '\n' +
signedresourcetype + '\n' +
'\n' +
signedexpiry + '\n' +
'\n' +
signedProtocol + '\n' +
signedversion + '\n';
const crypto =require('crypto')
const sig = crypto.createHmac('sha256', Buffer.from(key, 'base64')).update(StringToSign, 'utf8').digest('base64');
const sasToken =`sv=${(signedversion)}&ss=${(signedservice)}&srt=${(signedresourcetype)}&sp=${(signedpermissions)}&se=${encodeURIComponent(signedexpiry)}&spr=${(signedProtocol)}&sig=${encodeURIComponent(sig)}`;
const containerName=environment.containerName;
const pipeline =newPipeline (new AnonymousCredential(),{
retryOptions: { maxTries: 4 }, // Retry options
userAgentOptions: { userAgentPrefix: "AdvancedSample V1.0.0" }, // Customized telemetry string
keepAliveOptions: {
// Keep alive is enabled by default, disable keep alive by setting false
enable: false
}
});
const blobServiceClient =new BlobServiceClient(`https://${accountname}.blob.core.windows?${sasToken}`,
pipeline )
const containerClient =blobServiceClient.getContainerClient(containerName)
if(!containerClient.exists()){
console.log("the container does not exit")
await containerClient.create()
}
const client = containerClient.getBlockBlobClient(this.currentFile.name)
const response = await client.uploadBrowserData(this.currentFile,{
blockSize: 4 * 1024 * 1024, // 4MB block size
concurrency: 20, // 20 concurrency
onProgress: (ev) => console.log(ev),
blobHTTPHeaders :{blobContentType:this.currentFile.type}
})
console.log(response._response.status)
}
}
- Configure CORS for Azure storage
Allowed origins: *
Allowed verbs: DELETE,GET,HEAD,MERGE,POST,OPTIONS,PUT
Allowed headers: *
Exposed headers: *
Maximum age (seconds): 86400
- Test. I upload a pdf file
Regarding how to configure CORS, please refer to the following steps
Sign in Azure Portal.
Select the Azure account you use
Configure CORS
Update
If you cannot use function createHmac
, you can try to use crypto-js
. The detailed steps are as below
- install sdk
npm install crypto-js --save
npm install @types/crypto-js --save-dev
- Update code in the in app.ponent.ts
...
import * as CryptoJS from 'crypto-js';
...
export class AppComponent {
title = 'web1';
currentFile : File =null;
onFileChange(event) {
this.currentFile = event.target.files[0];
console.log(this.currentFile.name)
console.log(this.currentFile.type)
// generate account sas token
const accountName =environment.accountName;
const key=environment.key;
const start = new Date(new Date().getTime() - (15 * 60 * 1000));
const end = new Date(new Date().getTime() + (30 * 60 * 1000));
const signedpermissions = 'rwdlac';
const signedservice = 'b';
const signedresourcetype = 'sco';
const signedexpiry = end.toISOString().substring(0, end.toISOString().lastIndexOf('.')) + 'Z';
const signedProtocol = 'https';
const signedversion = '2018-03-28';
const StringToSign =
accountName+ '\n' +
signedpermissions + '\n' +
signedservice + '\n' +
signedresourcetype + '\n' +
'\n' +
signedexpiry + '\n' +
'\n' +
signedProtocol + '\n' +
signedversion + '\n';
var str =CryptoJS.HmacSHA256(StringToSign,CryptoJS.enc.Base64.parse(key));
var sig = CryptoJS.enc.Base64.stringify(str);
const sasToken =`sv=${(signedversion)}&ss=${(signedservice)}&srt=${(signedresourcetype)}&sp=${(signedpermissions)}&se=${encodeURIComponent(signedexpiry)}&spr=${(signedProtocol)}&sig=${encodeURIComponent(sig)}`;
const containerName=environment.containerName;
const pipeline =newPipeline (new AnonymousCredential(),{
retryOptions: { maxTries: 4 }, // Retry options
userAgentOptions: { userAgentPrefix: "AdvancedSample V1.0.0" }, // Customized telemetry string
keepAliveOptions: {
// Keep alive is enabled by default, disable keep alive by setting false
enable: false
}
});
const blobServiceClient =new BlobServiceClient(`https://${accountname}.blob.core.windows?${sasToken}`,
pipeline )
const containerClient =blobServiceClient.getContainerClient(containerName)
if(!containerClient.exists()){
console.log("the container does not exit")
await containerClient.create()
}
const client = containerClient.getBlockBlobClient(this.currentFile.name)
const response = await client.uploadBrowserData(this.currentFile,{
blockSize: 4 * 1024 * 1024, // 4MB block size
concurrency: 20, // 20 concurrency
onProgress: (ev) => console.log(ev),
blobHTTPHeaders :{blobContentType:this.currentFile.type}
})
console.log(response._response.status)
}
}
本文标签: javascriptAdding File to Azure Storage Blob from AngularStack Overflow
版权声明:本文标题:javascript - Adding File to Azure Storage Blob from Angular - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741258496a2367150.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论