繁体   English   中英

如何在nodejs中将图像从pipe stream显示到img标签

[英]How to display an image from a pipe stream in nodejs to an img tag

我们有这段代码使用 GridFS 管道存储在 MongoDB 中的图像

exports.getOneVerificationImageByFilename = async (req, res, next) => {
  const image = await gfs.files.findOne({ filename: req.params.image });
  try {
    const readStream = gfs.createReadStream(image.filename);
    readStream.on("error", function (err) {
      res.send("No image found with that title");
    });
    res.contentType("image/png");
    readStream.pipe(res);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
};

我正在使用react ,我需要在<img/>标签中显示它。 我就是这样称呼这个端点的

const getImage = async filename => {
    try {
        const response = await axios.get(`/image/${filename}`);
        return response;
    } catch (error) {
        throw new Error(error)
    }
}

由于端点不返回任何res ,因此response为空。 然后我读到它正在流式传输数据块。 我发现有人使用这种语法:

<img src="<%= url %>" />

但是我不明白。 我需要在 img 标签中显示流式传输的块

我的回答可能会迟到,但这对我有用。 实际上,从浏览器中,您必须使用Streams API来访问和管理从服务器端接收的数据流。 不要使用 axios,而是使用Fetch API将响应公开为可读的 stream。

在这里,您将拥有 3 个函数: blobToBase64(blob)将 blob 转换为 base64 图像。 readImageFromStream(requestBody)将获取请求响应体作为参数,读取从服务器接收到的流,然后返回 base64 图像

function blobToBase64(blob) {
  return new Promise((resolve, _) => {
    const reader = new FileReader();
    reader.onloadend = () => resolve(reader.result);
    reader.readAsDataURL(blob);
  });
}



const readImageFromStream = async (fetchRequestResultBody) => {
      const reader = fetchRequestResultBody.getReader();
    
      const stream = new ReadableStream({
        start(controller) {
          return pump();
          // The following function handles each data chunk
          function pump() {
            // "done" is a Boolean and value a "Uint8Array"
            return reader.read().then(({ done, value }) => {
              // If there is no more data to read
              if (done) {
                console.log("done", done);
                controller.close();
                return;
              }
              // Get the data and send it to the browser via the controller
              controller.enqueue(value);
              return pump();
            });
          }
        },
      });
    
      const response = new Response(stream);
      const blob = await response.blob();
      // const url = URL.createObjectURL(blob);
      const base64 = await blobToBase64(blob);
    
      return base64;
    };

(async () => {
  const requestedData = await fetch(
    "http://localhost:3001/v2/medias/63270d49e260c93f70f527a0/featuredImage"
  );
  console.log(await readImageFromStream(requestedData.body));
})();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM