angular - 如何直接从 Angular 应用程序上传Azure Blob存储中的大文件

标签 angular azure-storage azure-blob-storage

我有天蓝色存储的连接字符串和容器名称。我想将一个大文件从我的 Angular 应用程序直接上传到天蓝色存储。我还想显示上传进度。我怎样才能做到这一点?

最佳答案

根据我的测试,如果您想上传文件到Azure blob,请引用以下步骤

  1. 创建一个 Angular Web 应用
ng new <appname>
  • 安装 Azure 存储 SDK
  • npm install @azure/storage-blob
    
  • 更新 app.component.html 文件
  • <div class="form-group">
      <label for="file">Choose File</label>
      <input type="file"
             id="file"
             (change)="onFileChange($event)">
    </div>
    
    
    
  • 更新环境.ts
  • export const environment = {
      production: false,
      accountName : "<account name>",
      containerName:"",
       key:""
    };
    
  • 在polyfills.ts中添加以下代码
  • (window as any).global = window;
    (window as any).process = require( 'process' );
    (window as any).Buffer = require( 'buffer' ).Buffer;
    
  • 在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];
        this.upload();
     }
    
     async upload(){
    // 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)
     }
    }
    
    

    7 测试。我上传了 1.3 GB video

    enter image description here

    enter image description here

    关于angular - 如何直接从 Angular 应用程序上传Azure Blob存储中的大文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60264886/

    相关文章:

    Angular 7 : Unit test Jasmine automate window size on mobile and web

    angular - 如何从 Firebase 检索数据以传递到 angularfire2/version-5 中的数组

    c# - 如何使用 Azure.Storage.Blobs BlobClient 检索 Blob 目录路径中的 Blob?

    javascript - 在使用配置文件而不是环境变量的 Node 应用程序中,应将 Azure 存储连接字符串放在何处?

    node.js - Karma 不会运行(socket.io 抛出错误)

    javascript - 错误 : Could not find source map for in Angular2, Karma、Webpack 和 Istanbul 尔

    node.js - 使用 Node 转换来自 Azure 表存储的响应

    azure - 如何在 Azure DevOps 中定义 Blob 存储触发器来创建新版本?

    azure - Azure 存储模拟器 (v4.2) 和 Micorosft.WindowsAzure.Storage (v7.0.0) => Azure SDK 2.9 的错误请求

    azure - 为 azure 数据库进行备份