首页 > 解决方案 > 在节点js中将缓冲区转换为文件的正确方法

问题描述

我想在调用 URL“/file/key”时显示来自 s3 存储桶的文件

app.get("/file/:key", getFileFromS3);

exports.getFileFromS3 = async (req, res, next) => {
  const s3 = new awsS3();
  const { key } = req.params;

  const data = await s3.getFileObject(key); //calling some other function
  console.log("data",data) 
  res.write(data.Body, "binary");
  res.end(null, "binary");
};

并且在控制台中查看的数据是

{
  AcceptRanges: 'bytes',
  LastModified: 2021-01-02T10:16:16.000Z,
  ContentLength: 140070,
  ETag: '"f1f9e2921a5fd0e3d748088f2df041f2"',
  ContentType: 'application/octet-stream',
  Metadata: {},
  Body: <Buffer 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 07 d0 00 00 03 e8 08 06 00 00 00 86 5e 65 aa 00 00 00 01 73 52 47 42 00 ae ce 1c e9 00 00 20 00 ... 140020 more bytes>
}

所以当我在浏览器中点击 URL https://npk-api.herokuapp.com/file/1609575283092_driver.png时,我能够看到图像。

但是当我将该 URL 提供给第三方 (SIGNZY) 时,它会说

verify Failed Only image(s)/pdf(s) are allowed, one of the urls does not respond like an image

但是当我在在线网站上上传相同的图像并获得链接即https://i.ibb.co/QYn0j82/driver.png 时,SIGNZY 不会抛出任何错误..

所以很明显,当我们点击https://npk-api.herokuapp.com/file/1609575283092_driver.png时我没有正确发送响应

有人可以帮我解决这个问题吗..

注意:我需要一个适用于图像和 pdf 的通用解决方案。

更新:

s3.getObject(params)
    .on('httpHeaders', function (statusCode, headers) {
        res.set('Content-Length', headers['content-length']);
        res.set('Content-Type', headers['content-type']);
        this.response.httpResponse.createUnbufferedStream()
            .pipe(res);
    })
    .send();

标签: node.jsbuffer

解决方案


推荐阅读