从Angular将文件添加到Azure存储Blob [英] Adding File to Azure Storage Blob from Angular

查看:77
本文介绍了从Angular将文件添加到Azure存储Blob的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出如何使用

I'm trying to figure out how to upload an image using ngx-awesome-uploader to azure storage blob from Angular.

我希望能够使用此库将其从angular直接发送到azure存储blob.我已经能够毫无问题地将其发送到我的nodejs后端,但是将其直接发送到blob存储对我来说一直是一个挑战.谁能提供一个可行的示例来说明如何做到这一点?感谢您的帮助!

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 ngx很棒的上传器示例

文件被传递给此文件. (控制台在代码下方输出)

The file is passed to this. (Console output below code)

import { FilePreviewModel } from 'ngx-awesome-uploader';
import { HttpRequest, HttpClient, HttpEvent, HttpEventType } from '@angular/common/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.com';
    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;
        }
      })
      );
  }

}

文件输出的console.output是

the console.output of FILE OUTPUT is

推荐答案

根据我的测试,如果要将文件上传到Azure blob,请参考以下步骤

According to my test, if you want to upload file to Azure blob, please refer to the following steps

  1. 安装Azure存储SDk

npm install @azure/storage-blob

  1. 更新app.component.html文件

<div class="form-group">
  <label for="file">Choose File</label>
  <input type="file"
         id="file"
         (change)="onFileChange($event)">
</div>


  1. 更新Environment.ts

export const environment = {
  production: false,
  accountName : "<account name>",
  containerName:"",
   key:""
};

  1. 在polyfills.ts中添加以下代码

(window as any).global = window;
(window as any).process = require( 'process' );
(window as any).Buffer = require( 'buffer' ).Buffer;

  1. 在app.component.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.component.html',
  styleUrls: ['./app.component.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.net?${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)
 }
}

  1. 为Azure存储配置CORS

Allowed origins: *
Allowed verbs: DELETE,GET,HEAD,MERGE,POST,OPTIONS,PUT
Allowed headers: *
Exposed headers: *
Maximum age (seconds): 86400

  1. 测试.我上传了pdf文件
  1. Test. I upload a pdf file


关于如何配置CORS,请参考以下步骤


Regarding how to configure CORS, please refer to the following steps

  1. 登录 Azure门户网站.

选择您使用的Azure帐户

Select the Azure account you use

配置CORS

如果无法使用功能createHmac,则可以尝试使用crypto-js.详细步骤如下

If you cannot use function createHmac, you can try to use crypto-js. The detailed steps are as below

  1. 安装SDK

npm install crypto-js --save
npm install @types/crypto-js --save-dev

  1. 更新app.component.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.net?${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)
 }
}

这篇关于从Angular将文件添加到Azure存储Blob的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆