【问题标题】:Cannot send PNG via express route无法通过特快路线发送 PNG
【发布时间】:2020-08-17 06:54:19
【问题描述】:

我有一个从我的 express 端点提供的 png 图像,该图像应该作为图像源可读。我目前已将图像作为节点中的缓冲区,我正在尝试渲染它,但我似乎无法让图像出现。

结果

预期

表达 JS 代码

publicController.get('/avatar', async (req, res, next) => {
  const image = await PUBLIC.avatar();
  res.writeHead(200, {
      'Content-Type': 'image/png',
      'Content-Length': image.toString("binary").length
    });
  res.charset = 'binary';
  res.write(image.toString("binary"));
  res.end()
})

尝试过的方法:

  • 从可读流进行管道传输
  • 转换为 base 64 并渲染
  • 转换为二进制和管道
  • 转换为二进制并渲染
  • 转储原始 png 文件

注意事项:

  • 我检查了 PNG 文件是正确的,我从缓冲区创建了一个文件,并且 PNG 呈现完美。
  • png 图像是动态的,取决于几个因素,因此我不能将其放入像 s3 这样的对象存储中。

【问题讨论】:

  • image .toBuffer() 的结果吗?因为sharp中没有.toString()@

标签: node.js image express npm sharp


【解决方案1】:
res.write(image.toString("binary"));

这不合适。如果您已经有缓冲区,请不要转换它。马上写出来。

res.writeHead(200, {
  'Content-Type': 'image/png',
  'Content-Length': image.length;
});
res.end(image);

【讨论】:

    【解决方案2】:

    你试过了吗?

    // assuming image is a Buffer
      res.writeHead(200, {
          'Content-Type': 'image/png' // drop Content-Length as it should be automatically added by express
        });
      res.end(image);
    

    【讨论】:

    • Express 不应该计算 Content-Length... 在这种情况下它应该以分块传输模式发送。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-01
    • 1970-01-01
    相关资源
    最近更新 更多