我使用rails,socket.io和节点构建了一个聊天服务器,允许用户相互发送图像,我正试图使用Amazon s3。以下是来自客户端和服务器的相关代码段:
客户端:
var img_file = this.files[0]; //retrieved from file input
file_reader.onload = function(e) {
//console.log(img_file);
var extension = img_file.name.split('.');
extension = extension[extension.length-1];
get_user_id(username, function(to_id) {
socket.emit('message', {
from: "<%= @user.displayname %>",
fromid: <%= @user.id %>,
to: username,
toid: parseInt(to_id),
content: e.target.result,
type: 'image',
extension: extension,
size: img_file.size
});
})
};
file_reader.readAsBinaryString(img_file);
服务器:
socket.on('message', function(message) {
console.log(message.type + " message received, sending to appropriate person: " + message.to);
if (message.type == 'text') {
//send message like normal
sendMessage(message);
}
else {
//it's an image, need additional processing
var blank_file = uuid.v4() + '-' + new Date().getTime() + '.' + message.extension;
var contents = message.content;
s3.putObject({
Bucket: 'bucket-name', //not the real bucket name
Key: blank_file,
ContentType: 'image/' + message.extension,
//ContentLength: message.size,
Body: contents
},
function(err, data) {
if (err) {
console.log(err)
}
else {
console.log('file uploaded to s3 successfully');
message.content = getS3Url(blank_file);
sendMessage(message);
}
})
}
}
每当我尝试使用此代码上传图像时,它似乎都有效,但是当我检查我的s3存储桶并打开图像时,我的操作系统会说该文件不可读或已损坏。我尝试过使用ContentLength参数,但是当我使用它时,我收到错误“BadDigest:您指定的Content-MD5与我们收到的内容不匹配”。
任何人都可以帮助我吗?我让这段代码正常工作没有 s3,但由于某种原因,自从我开始使用它以来,我一直收到损坏或无法识别的文件。
答案 0 :(得分:0)
I figured out what was wrong. You need to use a binary buffer to pass the data to s3 instead of just passing the string as is, so basically use these for the s3 parameters:
s3.putObject({
Bucket: 'bucket-name',
Key: file,
Body: new Buffer(contents, 'binary') //use a buffer to pass the data over
}, function() { });
By using the buffer, it should upload the files properly.