繁体   English   中英

来自AWS S3 Bucket的NodeJS下载文件

[英]NodeJS download file from AWS S3 Bucket

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

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

我想知道我在做什么是正确的,也是一个好习惯。 还想知道在“网络”选项卡中查看输出流是否正常。

我应该如何使用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); } 

在客户端,我可以看到:

在此输入图像描述

我认为问题在于标题:

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

暂无
暂无

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

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