簡體   English   中英

Azure Blob Node.js 下載 Blob 文件

[英]Azure Blob Node.js download blob files

我在 Angular 中有帶有前端的 node.js 應用程序,我需要將文件上傳和下載到 Azure blob/azure 存儲

我已按照此處給出的說明進行操作: https : //github.com/Azure/azure-sdk-for-js/blob/master/sdk/storage/storage-blob/samples/typescript/src/basic.ts

現在,當我下載它時,它會讀取可讀流中的圖像或文件,如何從 azure blob 下載文件

下面是我的代碼,其中列出了 blob 讀取到可讀流

const { BlobServiceClient, StorageSharedKeyCredential, BlobDownloadResponseModel } = require('@azure/storage-blob');

const uuidv1 = require('uuid/v1');

async ListBlob(req,res){
    const blobServiceClient = await BlobServiceClient.fromConnectionString(this.AZURE_STORAGE_CONNECTION_STRING);
    const container = blobServiceClient.getContainerClient('mycontainer');
    const containerClient = await blobServiceClient.getContainerClient(container.containerName);
    let temp = Array();
    // List the blob(s) in the container.
    for await (const blob of containerClient.listBlobsFlat()) {
        temp.push(blob.name);
    }
    const blockBlobClient = containerClient.getBlockBlobClient(temp[2]);
    const downloadBlockBlobResponse = await blockBlobClient.download(0);
    let result = await this.streamToString(downloadBlockBlobResponse.readableStreamBody!);
    res.send(result);

}

async streamToString(readableStream) {
  return new Promise((resolve, reject) => {
    const chunks = [];
    readableStream.on("data", (data) => {
      chunks.push(data.toString());
    });
    readableStream.on("end", () => {
      resolve(chunks.join(""));
    });
    readableStream.on("error", reject);
  });
}

請嘗試BlockBlobClient.downloadToFile()方法

  const response = await blockBlobClient.downloadToFile("filePath");

如果您的目標是將流寫入本地文件,那么您需要做的就是將流讀取為buffer並使用fs模塊將其保存在文件中。

基本上你可以嘗試這樣的事情:

const fs = require('fs');

async streamToLocalFile(readableStream) {
  return new Promise((resolve, reject) => {
    let buffer = Buffer.from([]);
    readableStream.on("data", (data) => {
        buffer = Buffer.concat([buffer, data], buffer.length+data.length);//Add the data read to the existing buffer.
    });
    readableStream.on("end", () => {
        fs.writeFileSync('your file path', buffer);//Write buffer to local file.
        resolve('your file path);//Return that file path.  
    });
    readableStream.on("error", reject);
  });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM