簡體   English   中英

如何使用javascript從stringstream內容azure blob存儲下載png文件

[英]How to download png file from stringstream content azure blob storage using javascript

我寫了這段代碼來獲取數據,我得到了這樣的響應

async function 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);
  });
}

if (type == "download") {
  const name = req.query.name || req.body.name;
  const itemname = req.query.itemname || req.body.itemname;
  var container = name ? name : "securesharecc";
  const containerClient = await blobServiceClient.getContainerClient(container);
  const blobName = itemname ? itemname : "sample.png";
  const blockBlobClient = containerClient.getBlockBlobClient(blobName);
  const downloadBlockBlobResponse = await blockBlobClient.download(0);
  console.log("\nDownloaded blob content...");
  var a = await streamToString(downloadBlockBlobResponse.readableStreamBody);
  console.log("\t", a);
  context.res = {
    body: { data: a }
  };
  context.done();
}

因此,此代碼使用 azure 容器中的項目名稱下載文件。

但我收到這樣的回復

{
  "data": "PNG\r\n\u001a\n\u0000\u0000\u0000\rIHDR\u0000\u0000\u0002�\u0000\u0000\u0001�\b\u0002\u0000\u0000\u0000\u000f�\u001fl\u0000\u0000\u0000\u0001sRGB\u0000��\u001c�\u0000\u0000\u0000\u0004gAMA\u0000\u0000��\u000b ....."
}

我想直接下載這個文件而不是顯示內容,怎么做?

請嘗試將您的streamToString方法更改為以下內容:

async function streamToString(readableStream) {
  return new Promise((resolve, reject) => {
    let chunks = Buffer.from([]);
    readableStream.on("data", (data) => {
      chunks = Buffer.concat([chunks, data], chunks.length + data.length);
    });
    readableStream.on("end", () => {
      resolve(chunks);
    });
    readableStream.on("error", reject);
  });
}

本質上,圖像文件是二進制文件,您不應該嘗試將其數據轉換為字符串。

暫無
暫無

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

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