2012-04-20 53 views
1

我的節點js代碼從我的服務器tmp.png打開一個本地png文件,然後嘗試將其保存到亞馬遜S3。我一直遇到問題,我懷疑它與編碼有關。它唯一的工作方式是使用base64編碼(我不想爲我的照片編碼)。Cant的保存圖像與awssum和nodejs到亞馬遜S3

fs = require('fs'); 
var awssum = require('awssum'); 
var amazon = awssum.load('amazon/amazon'); 
var s3Service = awssum.load('amazon/s3'); 

var s3 = new s3Service('mykey', 'mysecret', 'account', amazon.US_WEST_1); 

fs.readFile('./tmp.png', function (err, data){ 
    if(err){ 
     console.log("There was an error opening the file"); 
    } else { 
     s3.PutObject({ 
      BucketName : 'my-bucket', 
      ObjectName : 'tmp.png', 
      ContentType : 'image/png', 
      ContentLength : data.length, 
      Body   : data, 
     }, function(err, data) { 
      if(err){ 
       console.log("There was an error writing the data to S3:"); 
       console.log(err); 
      } else { 
       console.log("Your data has been written to S3:"); 
       console.log(data); 
      } 
     }); 
    } 

}); 

顯然我的水桶實際上是我獨特的水桶名稱。我從亞馬遜返回的消息是請求超時:

您的與服務器的套接字連接在超時期限內未讀取或寫入。空閒連接將被關閉。

+0

注意,這個代碼是從約V0.4使用AwsSum(我的圖書館)的舊版本。新版本v0.5及更高版本的語法略有不同,因此值得關注AwsSum附帶的示例/文件夾。 – chilts 2012-07-25 03:33:58

回答

2

看起來像在文檔中發現的一個例子,它可以滿足我的需求。關鍵是要使用fs.stat的文件大小和fs.createReadStream文件中讀取:

// you must run fs.stat to get the file size for the content-length header (s3 requires this) 
fs.stat(path, function(err, file_info) { 
    if (err) { 
     inspect(err, 'Error reading file'); 
     return; 
    } 

    var bodyStream = fs.createReadStream(path); 

    console.log(file_info.size); 

    var options = { 
     BucketName : 'my-bucket', 
     ObjectName : 'test.png', 
     ContentType : 'image/png', 
     ContentLength : file_info.size, 
     Body   : bodyStream 
    }; 

    s3.PutObject(options, function(err, data) { 
     console.log("\nputting an object to my-bucket - expecting success"); 
     inspect(err, 'Error'); 
     inspect(data, 'Data'); 
    }); 
}); 
+0

即使上面的代碼不適合我。我仍然收到Request Timeout錯誤。任何想法? – 2013-09-26 13:18:20