2014-03-05 304 views
17

我正在寫從URL下載圖像的應用程序,然後將其上傳到使用aws-sdk的S3桶。文件,並將其上傳到AWS S3沒有保存 - Node.js的

Perviously我只是下載圖像,並將它們保存到磁盤這樣。

request.head(url, function(err, res, body){ 

    request(url).pipe(fs.createWriteStream(image_path)); 

}); 

然後上傳圖像到AWS S3這樣

fs.readFile(image_path, function(err, data){ 
    s3.client.putObject({ 
     Bucket: 'myBucket', 
     Key: image_path, 
     Body: data 
     ACL:'public-read' 
    }, function(err, resp) { 
     if(err){ 
      console.log("error in s3 put object cb"); 
     } else { 
      console.log(resp); 
      console.log("successfully added image to s3"); 
     } 
    }); 
}); 

但我想跳過部分,我將圖像保存到磁盤。有沒有辦法我可以piperequest(url)到一個變量的響應然後上傳呢?

回答

16

下面是一些JavaScript,這是否很好:

var options = { 
     uri: uri, 
     encoding: null 
    }; 
    request(options, function(error, response, body) { 
     if (error || response.statusCode !== 200) { 
      console.log("failed to get image"); 
      console.log(error); 
     } else { 
      s3.putObject({ 
       Body: body, 
       Key: path, 
       Bucket: 'bucket_name' 
      }, function(error, data) { 
       if (error) { 
        console.log("error downloading image to s3"); 
       } else { 
        console.log("success uploading to s3"); 
       } 
      }); 
     } 
    }); 
+6

書面的代碼加載整個身體成內存一次(作爲一個字符串進入「body」變量)。也就是說,這不會直接從請求流到S3。 OTOH,如果「編碼」爲空,請求將爲「body」創建一個Buffer對象;請參閱https://github.com/request/request#requestoptions-callback。我建議編輯這個答案,將'encoding:'binary''更改爲'encoding:null'並消除'body = new Buffer(body,'binary')'。這將消除將整個「身體」存儲在記憶中的需要,我認爲這符合原始問題和答案。但評論想評論... –

+1

我想你的做法,都與隱性和顯性編碼,我發現我上傳的PNG文件損壞,由於某種原因,無法找出原因。試圖複製這一形象https://openclipart.org/image/250px/svg_to_png/264091/MirrorCarp.png,這就是我得到我鬥http://images.quickhunts.com/clipart/23234234234.png –

+0

@ Ilanlewin它絕對與'png'圖像一起工作,但要確保正確執行'fs.readFile'。從我最初寫這個答案開始,它可能已經發生了變化,您可能需要更加具體地使用編碼。也可能嘗試一些'JPG'或其他通用圖像。 – Loourr

0

這是我做的,並很好地工作:

const request = require('request-promise') 
 
const AWS = require('aws-sdk') 
 
const s3 = new AWS.S3() 
 

 
const options = { 
 
    uri: uri, 
 
    encoding: null 
 
}; 
 

 
async load() { 
 

 
    const body = await request(options) 
 
    
 
    const uploadResult = await s3.upload({ 
 
    Bucket: 'bucket_name', 
 
    Key : path, 
 
    Body : body, 
 
    }).promise() 
 
    
 
}

相關問題