我正在尝试编写一个使用 node.js 将图像存储在 s3 上的图像服务器。上传图像工作正常,我可以使用 s3 浏览器客户端正确下载和查看它(我使用的是 Dragondisk,具体来说,但我也已经成功下载了它与其他的),但是当我使用节点下载它并尝试要将其写入磁盘,我无法打开文件(它说它可能已损坏或使用预览无法识别的文件格式)。我正在使用 amazon sdk for node 和 fs 来编写文件。我知道您可以将可选编码传递给 fs.writeFile,但我已经尝试了所有方法,但它不起作用。我还尝试在 putObject 上设置 ContentType,在 getObject 上设置 ResponseContentType,以及 ContentEncoding 和 ResponseContentEncoding(以及所有这些东西的各种组合)。结果相同。这里'
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}));
});
};
顺便说一句,我使用 express 进行路由,所以这就是 req.params 的来源。