如何在浏览器中使用JS访问Azure Blob存储

时间:2020-04-20 02:33:48

标签: javascript azure azure-blob-storage

我正在尝试访问Web应用程序(Vue)中的Azure Blob存储。
但是,出现以下错误:

捕获:仅在Node.js环境中支持帐户连接字符串

如何访问Azure Blob存储?
我进行了调查,但不确定是什么原因。 谁能告诉我?


code.vue

const { BlobServiceClient } = require("@azure/storage-blob");

mounted: function () {
  this.init()
},
methods: {
  init: function () {
    this.accessBlob()
        .then(() => console.log('Done'))
        .catch((ex) => console.log('catch:', ex.message));
    },
  accessBlob: async function(){
      const config = require("./config/config.json");
      const AZURE_STORAGE_CONNECTION_STRING = config.storageAccountOrConnectionString;

      const blobServiceClient = await BlobServiceClient.fromConnectionString(AZURE_STORAGE_CONNECTION_STRING);
      console.log(blobServiceClient);
    }
  }

1 个答案:

答案 0 :(得分:1)

根据official document,当使用方法BlobServiceClient.fromConnectionString连接Azure blob时,帐户连接字符串只能在 NODE.JS 运行时中使用。 br /> enter image description here

因此,我建议我们使用sas令牌连接Azure blob存储。例如

  1. 创建sas令牌(我使用sdk crypto-js来创建它)
import * as CryptoJS from 'crypto-js';

 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)}`;

  1. 连接Azure Blob
import {
BlobServiceClient
  AnonymousCredential,
  newPipeline
} from "@azure/storage-blob";



const pipeline = newPipeline(new AnonymousCredential());
 const blobServiceClient =new BlobServiceClient(`https://${accountname}.blob.core.windows.net?${sasToken}`,
                                                             pipeline  )