Reactjs如何从Azure存储容器下载文件

问题描述

我正在处理reactjs/typescript应用程序。我正在尝试从Azure Storage v2下载一些文件。以下是我应该下载文件的示例路径。在此路径中,扩展是容器名称,其余的都是文件夹。我正在尝试从reportdocument文件夹中下载最后修改文件

enrichment/report/SAR-1234-56/reportdocument/file1.docs

我尝试了以下操作。

@action
    public async reportDownload(sarNumber: string) {
        let storage = globals.getGlobals('StorageAccount03');
        console.log(storage);
        let containerName = globals.getGlobals('StorageAccount03ContainerName');
        let marker = undefined;
        let allUploadPromise: Array<Promise<unkNown>> = [];
        const config = {
            path: `/Storage/getsastoken/?storageName=${storage}&containerName=${containerName}`,method: "GET",success: (url: any) => {

                const containerURL: ContainerURL = new ContainerURL(
                    url,StorageURL.newPipeline(new AnonymousCredential()));
                 
                const listBlobsResponse =  containerURL.listBlobFlatSegment(
                    Aborter.none,marker,);
            }
        };
        await handleRequest(config);
    }

我正在努力从上述路径下载最新的修改文件。 有人可以帮我解决这个问题吗?任何帮助将不胜感激。谢谢

解决方法

最好使用@azure/storage-blob库,然后代码如下所示,而不是像尝试代码那样直接尝试调用blob REST API,这似乎是不必要的。该库已经为您完成了。有关详细信息,请参见this

const { BlobServiceClient } = require("@azure/storage-blob");
 
const account = "<account name>";
const sas = "<service Shared Access Signature Token>";
const containerName = "<container name>";
const blobName = "<blob name>";
 
const blobServiceClient = new BlobServiceClient(`https://${account}.blob.core.windows.net${sas}`);
 
async function download() {
  const containerClient = blobServiceClient.getContainerClient(containerName);
  const blobClient = containerClient.getBlobClient(blobName);
 
  // Get blob content from position 0 to the end
  // In browsers,get downloaded data by accessing downloadBlockBlobResponse.blobBody
  const downloadBlockBlobResponse = await blobClient.download();
  const downloaded = await blobToString(await downloadBlockBlobResponse.blobBody);
  console.log("Downloaded blob content",downloaded);
 
  // [Browsers only] A helper method used to convert a browser Blob into string.
  async function blobToString(blob) {
    const fileReader = new FileReader();
    return new Promise((resolve,reject) => {
      fileReader.onloadend = (ev) => {
        resolve(ev.target.result);
      };
      fileReader.onerror = reject;
      fileReader.readAsText(blob);
    });
  }
}