昨天我做了一个深夜编码会话并创建了一个小node.js / JS(实际上是CoffeeScript,但CoffeeScript只是JavaScript,所以就是说JS)app。
目标是什么:
第1步已完成。
服务器现在有一个字符串a la
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACt...
我的问题是:我将此数据“流式传输”/上传到Amazon S3并在那里创建实际图像的下一步是什么?
knox https://github.com/LearnBoost/knox似乎是一个很棒的库,可以将某些内容输入S3,但我缺少的是base64-encoded-image-string和实际上传操作之间的粘合?
欢迎任何想法,指示和反馈。
答案 0 :(得分:158)
对于仍在努力解决这个问题的人。这是我使用本机aws-sdk的方法。
var AWS = require('aws-sdk');
AWS.config.loadFromPath('./s3_config.json');
var s3Bucket = new AWS.S3( { params: {Bucket: 'myBucket'} } );
在路由器方法内: - ContentType应设置为图像文件的内容类型
buf = new Buffer(req.body.imageBinary.replace(/^data:image\/\w+;base64,/, ""),'base64')
var data = {
Key: req.body.userId,
Body: buf,
ContentEncoding: 'base64',
ContentType: 'image/jpeg'
};
s3Bucket.putObject(data, function(err, data){
if (err) {
console.log(err);
console.log('Error uploading data: ', data);
} else {
console.log('succesfully uploaded the image!');
}
});
s3_config.json文件是: -
{
"accessKeyId":"xxxxxxxxxxxxxxxx",
"secretAccessKey":"xxxxxxxxxxxxxx",
"region":"us-east-1"
}
答案 1 :(得分:17)
在我的代码
中基本上看起来像这样buf = new Buffer(data.dataurl.replace(/^data:image\/\w+;base64,/, ""),'base64')
req = knoxClient.put('/images/'+filename, {
'Content-Length': buf.length,
'Content-Type':'image/png'
})
req.on('response', (res) ->
if res.statusCode is 200
console.log('saved to %s', req.url)
socket.emit('upload success', imgurl: req.url)
else
console.log('error %d', req.statusCode)
)
req.end(buf)
答案 2 :(得分:1)
可接受的答案非常有用,但是如果有人需要接受任何文件而不只是图像,则此正则表达式非常有用:
/^data:.+;base64,/
答案 3 :(得分:1)
这是我遇到的一篇文章的代码,发布在下面:
const imageUpload = async (base64) => {
const AWS = require('aws-sdk');
const { ACCESS_KEY_ID, SECRET_ACCESS_KEY, AWS_REGION, S3_BUCKET } = process.env;
AWS.config.setPromisesDependency(require('bluebird'));
AWS.config.update({ accessKeyId: ACCESS_KEY_ID, secretAccessKey: SECRET_ACCESS_KEY, region: AWS_REGION });
const s3 = new AWS.S3();
const base64Data = new Buffer.from(base64.replace(/^data:image\/\w+;base64,/, ""), 'base64');
const type = base64.split(';')[0].split('/')[1];
const userId = 1;
const params = {
Bucket: S3_BUCKET,
Key: `${userId}.${type}`, // type is not required
Body: base64Data,
ACL: 'public-read',
ContentEncoding: 'base64', // required
ContentType: `image/${type}` // required. Notice the back ticks
}
let location = '';
let key = '';
try {
const { Location, Key } = await s3.upload(params).promise();
location = Location;
key = Key;
} catch (error) {
}
console.log(location, key);
return location;
}
module.exports = imageUpload;
了解更多:http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property
积分:https://medium.com/@mayneweb/upload-a-base64-image-data-from-nodejs-to-aws-s3-bucket-6c1bd945420f