Javascript res.从AmazonS3下载文件

Javascript res.从AmazonS3下载文件,javascript,node.js,amazon-web-services,file,express,Javascript,Node.js,Amazon Web Services,File,Express,我试图从根目录外下载一个文件,但每次我尝试时,它都试图从根目录中获取该文件。我需要我的网站的用户能够下载这些文件 该文件最初已上载到AmazonS3,我使用getObject函数访问了它 这是我的密码: app.get('/test_script_api', function(req, res){ var fileName = req.query.File; s3.getObject( { Bucket: "bucket-name", Key: fileName

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

该文件最初已上载到AmazonS3,我使用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);
            }
        }
    );
});
这将返回以下错误: 错误:enoint:没有这样的文件或目录,stat'/home/ec2 user/environment/test2.txt'

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

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

有没有更简单的方法从AmazonS3下载文件


在此,任何帮助都将不胜感激

我也有同样的问题,我找到了这个答案:

基于此,您需要使用createReadStream和管道。 R这里有更多关于stream.pipe的信息-

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);
});
在我的情况下,在客户端,我使用 这确保了文件正在下载