Cant 使用 awssum 和 nodejs 将映像保存到 Amazon S3

Cant's save image with awssum and nodejs to amazon S3

本文关键字:保存 Amazon S3 映像 使用 awssum nodejs Cant      更新时间:2023-09-26

我的节点js代码从我的服务器tmp.png打开一个本地png文件,然后尝试将其保存在Amazon S3中。我一直遇到问题,我怀疑这与编码有关。它工作的唯一方法是使用 base64 编码(我不希望我的照片使用)。

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);
            }
        });
    }
});

显然,我的存储桶实际上是我唯一的存储桶名称。我从亚马逊收到的消息是请求超时:

在超时期限内未读取或写入与服务器的套接字连接。空闲连接将关闭。

看起来在

文档中找到了一个示例,可以完成我需要它的功能。关键是使用 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');
    });
});