javascript - NodeJS 从 AWS S3 存储桶下载文件

标签 javascript node.js amazon-web-services express amazon-s3

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

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

QUESTION

I'm wondering if what I'm doing is correct and a good practice. Also would like to know if it's normal to see the output stream in the Network tab.

How should I properly send I file from S3 to my client application using NodeJS/Express?

我很确定其他网站请求不会让您预览内容并显示以下内容:“无法加载响应数据”。

<小时/>

这是我在 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);
}

在客户端我可以看到这个:

enter image description here

最佳答案

我认为问题出在标题上:

          //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);

所以代码应该是这样的(这就是我在项目处理文件中作为 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);
        }
      });
    });

关于javascript - NodeJS 从 AWS S3 存储桶下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55705550/

相关文章:

javascript - 链接到路由中的 react 路由器和 typescript "match"问题

javascript - 为什么使用 32 位 BufferView 时 TypedArray 访问速度更快?

javascript - 将文件从express js传输到另一台服务器

javascript - Object.defineProperty 有时会抛出异常

python - AWS Lambda TypeError : datetime. datetime(2012, 8, 8, 21, 46, 24, 862000) 不是 JSON 可序列化

amazon-web-services - AWS 政策 : Allow update specific record in route53 hosted zone

javascript - 当选项更改时如何在选择上执行更改事件?

node.js - 在exe中嵌入node.js网站

amazon-web-services - 下载期间 Amazon S3 链接过期?

javascript - 为什么在 asp.net mvc 中更改图像链接会异步调用 Controller