NodeJS 从 AWS S3 存储桶下载文件

Jos*_*lón 7 javascript amazon-s3 amazon-web-services node.js express

我正在尝试在 NodeJS/Express 中创建一个端点,用于从我的 AWS S3 存储桶下载内容。

它运行良好,我可以在客户端下载文件,但我也可以在“网络”选项卡中看到流预览,这很烦人......

问题

我想知道我所做的是否正确并且是一个好的做法。还想知道在“网络”选项卡中看到输出流是否正常。

我应该如何使用 NodeJS/Express 将文件从 S3 正确发送到我的客户端应用程序?

我很确定其他网站请求不允许您预览内容:“无法加载响应数据”。


这是我在 NodeJS 应用程序中从 AWS S3 获取流文件的操作:

download(fileId) {
  const fileObjectStream = app.s3
    .getObject({
      Key: fileId
    })
    .createReadStream();
  this.res.set("Content-Type", "application/octet-stream");
  this.res.set(
    "Content-Disposition",
    'attachment; filename="' + fileId + '"'
  );
  fileObjectStream.pipe(this.res);
}
Run Code Online (Sandbox Code Playgroud)

在客户端我可以看到:

在此输入图像描述

Ste*_*ign 4

我认为问题出在标题上:

          //this line will set proper header for file and make it downloadable in client's browser

          res.attachment(key); 

          // this will execute download 
          s3.getObject(bucketParams)
          .createReadStream()
          .pipe(res);
Run Code Online (Sandbox Code Playgroud)

所以代码应该是这样的(这就是我在项目处理文件中作为 res.attachment 或 res.json 所做的,以防出现错误,以便客户端可以向最终用户显示错误):

router.route("/downloadFile").get((req, res) => {
      const query = req.query; //param from client
      const key = query.key;//param from client
      const bucketName = query.bucket//param from client

      var bucketParams = {
        Bucket: bucketName,  
        Key: key
      };

      //I assume you are using AWS SDK
      s3 = new AWS.S3({ apiVersion: "2006-03-01" });

      s3.getObject(bucketParams, function(err, data) {
        if (err) {
          // cannot get file, err = AWS error response, 
          // return json to client
          return res.json({
            success: false,
            error: err
          });
        } else {
          res.attachment(key); //sets correct header (fixes your issue ) 
          //if all is fine, bucket and file exist, it will return file to client
          s3.getObject(bucketParams)
            .createReadStream()
            .pipe(res);
        }
      });
    });
Run Code Online (Sandbox Code Playgroud)