【问题标题】:How can I access Azure Blob Storage using JS in the browser如何在浏览器中使用 JS 访问 Azure Blob 存储
【发布时间】:2020-08-02 11:21:12
【问题描述】:

我正在尝试在 Web 应用 (Vue) 中访问 Azure Blob 存储。
但是,我收到以下错误:

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

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


代码.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);
    }
  }

【问题讨论】:

  • 这几乎就是错误所说的。您的代码在浏览器中运行,但您尝试使用的连接方法在 Web 环境中不受支持
  • 感谢您的教导。在这种情况下,如何改进从 vue.js 对 Azure Blob 存储的访问?如果您能告诉我,我将不胜感激。
  • @stkhr 您还有其他顾虑吗?如果您没有其他顾虑,可以请accept the answer吗?它可能会帮助更多有类似问题的人。

标签: javascript azure azure-blob-storage


【解决方案1】:

根据official document,当使用menthodBlobServiceClient.fromConnectionString连接Azure blob时,帐号连接字符串只能在NODE.JS运行时使用。
@987654322 @

所以我建议我们使用 sas 令牌连接 Azure blob 存储。例如

  1. 创建sas token(我使用sdkcrypto-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  )

【讨论】:

    猜你喜欢
    • 2011-06-18
    • 2021-12-13
    • 2023-04-07
    • 2013-01-28
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    • 2019-03-13
    • 1970-01-01
    相关资源
    最近更新 更多