我正在尝试编写一个使用node.js在s3上存储图像的图像服务器。上传图片效果很好,我可以使用s3浏览器客户端正确下载并查看它(我特别使用了dragondisk,但我也成功下载了它),但是当我用节点下载并尝试将其写入磁盘,我无法打开该文件(它表示可能已损坏或使用Preview无法识别的文件格式)。我正在使用amazon sdk for node和fs来编写文件。我知道你可以将一个可选的编码传递给fs.writeFile,但我已经试过了,它不起作用。我也尝试在putObject上设置ContentType和getContentType,以及ContentEncoding和ResponseContentEncoding(以及各种组合中的所有这些东西)。同样的结果。下面是一些代码:使用node.js保存存储在s3上的图像?
var AWS = require('aws-sdk')
, gm = require('../lib/gm')
, uuid = require('node-uui')
, fs = require('fs');
AWS.config.loadFromPath('./amazonConfig.json');
var s3 = new AWS.S3();
var bucket = 'myBucketName'; // There's other logic here to set the bucket name.
exports.upload = function(req, res) {
var id = uuid.v4();
gm.format("/path/to/some/image.jpg", function(format){
var key = req.params.dir + "/" + id + "/default." + format;
fs.readFile('/path/to/some/image.jpg', function(err, data){
if (err) { console.warn(err); }
else {
s3.client.putObject({
Bucket: bucket,
Key: key,
Body: data,
ContentType: 'image/jpeg'
// I've also tried adding ContentEncoding (in various formats) here.
}).done(function(response){
res.status(200).end(JSON.stringify({ok:1, id: id}));
}).fail(function(response){
res.status(response.httpResponse.statusCode).end(JSON.stringify(({err: response})));
});
}
});
});
};
exports.get = function(req, res) {
var key = req.params.dir + "/" + req.params.id + "/default.JPEG";
s3.client.getObject({
Bucket: bucket,
Key: key,
ResponseContentType: 'image/jpeg'
// Tried ResponseContentEncoding here in base64, binary, and utf8
}).done(function(response){
res.status(200).end(JSON.stringify({ok:1, response: response}));
var filename = '/path/to/new/image/default.JPEG';
fs.writeFile(filename, response.data.Body, function(err){
if (err) console.warn(err);
// This DOES write the file, just not as an image that can be opened.
// I've tried pretty much every encoding as the optional third parameter
// and I've matched the encodings to the ResponseContentEncoding and
// ContentEncoding above (in case it needs to be the same)
});
}).fail(function(response){
res.status(response.httpResponse.statusCode).end(JSON.stringify({err: response}));
});
};
顺便说一句,我用快递的路由,因此,这就是req.params从何而来。
我刚刚发现,如果我将'base64'作为编码传递给fs.readFile()和fs.writeFile(),则情况正好相反。我可以使用我的服务下载并查看图像,但如果使用s3浏览器客户端下载,则无法查看它。有两种做法吗? – tandrewnichols