【问题标题】:res.download file from Amazon S3从 Amazon S3 下载 res.download 文件
【发布时间】:2020-05-29 03:02:48
【问题描述】:

我正在尝试从我的根目录之外下载一个文件,但是每次我尝试时,它都会尝试从根目录中获取它。我需要我网站的用户才能下载这些文件。

该文件最初已上传到 Amazon S3,我已使用 getObject 函数访问它。

这是我的代码:

app.get('/test_script_api', function(req, res){
    var fileName = req.query.File;
    s3.getObject(
        { Bucket: "bucket-name", Key: fileName },
        function(error, s3data){
            if(error != null){
                console.log("Failed to retrieve an object: " + error);
            }else{
                //I have tried passing the S3 data but it asks for a string
                res.download(s3data.Body);

                //So I have tried just passing the file name & an absolute path
                res.download(fileName);
            }
        }
    );
});

这将返回以下错误: 错误:ENOENT:没有这样的文件或目录,stat '/home/ec2-user/environment/test2.txt'

当我输入绝对路径时,它只是将它附加到 /home/ec2-user/environment/ 的末尾

如何更改 res.download 尝试下载的目录?

有没有更简单的方法从 Amazon S3 下载文件?

任何帮助将不胜感激!

【问题讨论】:

    标签: javascript node.js amazon-web-services file express


    【解决方案1】:

    我遇到了同样的问题,我找到了这个答案: NodeJS How do I Download a file to disk from an aws s3 bucket?

    基于此,您需要使用 createReadStream() 和 pipe()。 R 这里更多关于 stream.pipe() - https://nodejs.org/en/knowledge/advanced/streams/how-to-use-stream-pipe/

    res.attachment() 将为您设置标题。 -> https://expressjs.com/en/api.html#res.attachment.

    此代码应该适合您(基于上面链接中的答案):

    app.get('/test_script_api', function (req, res) {
      var fileName = req.query.File;
      res.attachment(fileName);
      var file = s3.getObject({
        Bucket: "bucket-name",
        Key: fileName
        }).createReadStream()
          .on("error", error => {
          });
       file.pipe(res);
    });
    

    就我而言,在客户端,我使用了<a href="URL to my route" download="file name"></a> 这确保文件正在下载。

    【讨论】:

      猜你喜欢
      • 2014-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-10
      • 2012-08-29
      • 2013-07-29
      • 2013-05-08
      • 1970-01-01
      相关资源
      最近更新 更多