簡體   English   中英

從 Amazon S3 下載 res.download 文件

[英]res.download file from Amazon S3

我試圖從我的根目錄之外下載一個文件,但是每次我嘗試時,它都會嘗試從根目錄中獲取它。 我需要我網站的用戶才能下載這些文件。

該文件最初已上傳到 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 下載文件?

任何幫助將不勝感激!

我遇到了同樣的問題,我找到了這個答案: NodeJS 如何從 aws s3 存儲桶下載文件到磁盤?

基於此,您需要使用 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>這確保文件正在下載。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM