从Amazon S3下载文件

问题描述 投票:0回答:1

我正试图从我的根目录外下载一个文件,然而每次我尝试时,它都试图从根目录中获取。我将需要我网站的用户能够下载这些文件。

该文件最初已经上传到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);
            }
        }
    );
});

这将返回以下错误:Error: ENOENT: no such file or directory, stat 'homeec2-userenvironmenttest2.txt'

当我输入绝对路径时,它只是把这个附加到homeec2-userenvironment的结尾。

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

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

任何帮助都将在这里非常感激!

javascript node.js amazon-web-services file express
1个回答
1
投票

我有同样的问题,我发现这个答案。NodeJS如何从aws s3 bucket下载文件到磁盘?

基于此,你需要使用createReadStream()和pipe().R这里有更多关于stream.pipe()的内容------。https:/nodejs.orgenknowledgeadvancedstreamshow-to-use-stream-pipe。

res.attachment()将为你设置头文件。-&gt.Res.attachment()将为你设置头文件。https:/expressjs.comenapi.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>这确保了文件的下载。

© www.soinside.com 2019 - 2024. All rights reserved.