如何显示已保存为缓冲区的文件?

问题描述 投票:0回答:2

我将文件作为缓冲区保存在我的 mongo 数据库中(使用 mongoose、nodejs、Electron)。目前,我使用纯文本文件来保持简单。我使用

读取了一个文件
fs.readFile(filePath, function(err, data) {
    if (err) {console.log(err);}
    typeof callback == "function" && callback(data);
});

然后我使用

data
变量在数据库中创建一个新文件。而且,现在我的 mongodb 中存储了一些看起来像
BinData(0,"SGVsbG8gV29ybGQK")
的东西。到目前为止一切都很好。

现在,如果我想在 UI 中显示该文件怎么办?在这种情况下,在电子?我认为有两个步骤。

第 1 步 首先是将这个变量从数据库中取出并放入前端。仅供参考:该模型称为

File
,存储文件内容的变量称为
content

所以,我尝试过

File.content.toString()
,这给了我
Object {type: "Buffer", data: Array[7]}
,这不是我期待的字符串。这里发生了什么?我在here读到这应该可行。

步骤 2 显示此文件。现在,由于我现在只使用文本文件,因此我可以在步骤 1 运行后显示我得到的字符串。但是,对于更复杂的文件有没有好的方法呢?图片和 GIF 之类的?

node.js mongodb buffer electron
2个回答
0
投票

您应该保存文件 mime。

然后设置response.header MIME

response.setHeader("Content-Type", "image/jpeg");

response.write(binary)

response.end()

0
投票

将读取缓冲区转换为可读流,如下所示,然后发送到响应

function streamToBuffer(readableStream) {
  return new Promise((resolve, reject) => {
      const chunks = [];
      readableStream.on("data", (data) => {
          chunks.push(data instanceof Buffer ? data : Buffer.from(data));
      });
      readableStream.on("end", async() => {
          resolve(Buffer.concat(chunks));
      });
      readableStream.on("error", reject);
  });
}

const imageBuffer = await streamToBuffer(fileReadResponse)

response.setHeader("Content-Type", "image/jpeg");
response.write(imageBuffer)
response.end()
© www.soinside.com 2019 - 2024. All rights reserved.