Bellow是我用来使用NodeJS和aws-sdk将文件上传到S3的代码。一切似乎工作正常,但浏览器只是挂起。此外,当我尝试在S3上打开图像时,它会显示破碎。
module.exports = function(app) {
app.post('/upload', function(req, res){
var AWS = require('aws-sdk');
var accessKeyId = process.env.AWS_ACCESS_KEY;
var secretAccessKey = process.env.AWS_SECRET_KEY;
//pull var from heroku else send to dev
AWS.config.update({
accessKeyId: accessKeyId,
secretAccessKey: secretAccessKey
});
var s3 = new AWS.S3();
var file = req.files.filechooser;
if (file) {
var params = {
Bucket: 'mybucket',
Body: new Buffer(file, 'binary'),
ACL:'public-read',
ContentType: file.type,
Key: "ugc/" + file.name,
ContentLength: file.size
};
s3.putObject(params, function(err, data){
if (err) {
console.log("Error uploading data: ", err);
} else {
console.log("Successfully uploaded data to myBucket/myKey");
}
}).
on('httpUploadProgress', function(chunk) {
console.log("Uploaded", chunk.loaded, "of", chunk.total, "bytes");
}).
on('httpDone', function() {
console.log("done");
});
console.log("called");
} else {
console.log('Nothing to upload.');
}
});
}
答案 0 :(得分:1)
在为侦听器重新编程之后,您需要完成对putObject的调用,以实际使用send启动上载。默认情况下,如果向返回响应的S3方法提供回调,则必须使用send()手动启动请求;
on('httpUploadProgress', function(chunk) {
console.log("Uploaded", chunk.loaded, "of", chunk.total, "bytes");
}).
on('httpDone', function() {
console.log("done");
}).
send(); // Actually initiate the request
见
详情。