【问题标题】:How to download png file from stringstream content azure blob storage using javascript如何使用javascript从stringstream内容azure blob存储中下载png文件
【发布时间】:2022-01-12 07:44:56
【问题描述】:

我已经编写了这段代码来获取数据,我得到了这样的响应

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 base64string = await streamToString(downloadBlockBlobResponse.readableStreamBody);
  console.log("\t", base64string);
  context.res = {
    body: { data: base64string }
  };
  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 ....."
}

如果我想直接下载这个文件而不是显示内容,该怎么编码,怎么做?

【问题讨论】:

  • 您希望在响应中看到什么?也就是说,a{data: a} 中应该是什么?
  • 这里是base64string

标签: javascript node.js typescript azure


【解决方案1】:

请尝试将您的 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);
  });
}

图像文件本质上是二进制文件,您不应该尝试将其数据转换为字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 2015-06-20
    • 2021-12-08
    • 2018-01-08
    • 1970-01-01
    相关资源
    最近更新 更多