javascript 通过Node.js将base64编码的图像上传到Amazon S3

lhcgjxsq  于 2023-06-20  发布在  Java
关注(0)|答案(5)|浏览(117)

昨天我做了一个深夜编码会议,并创建了一个小的node.js/JS(实际上是CoffeeScript,但CoffeeScript只是JavaScript,所以让我们说JS)应用程序。
目标是什么
1.客户端向服务器发送canvas datauri(png)(通过socket.io)
1.服务器上传图像到亚马逊S3
完成步骤1。
服务器现在有一个字符串a la

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACt...

我的问题是:我下一步要将此数据“流式传输”/上传到Amazon S3并在那里创建实际映像,需要执行哪些步骤?
knox https://github.com/LearnBoost/knox看起来像是一个很棒的将东西放到S3的库,但是我缺少的是base64编码的图像字符串和实际上传操作之间的粘合剂
任何想法,指针和反馈欢迎。

pdsfdshx

pdsfdshx1#

对于那些仍然在这个问题上挣扎的人来说。以下是我在原生aws-sdk中使用的方法**:**

var AWS = require('aws-sdk');
AWS.config.loadFromPath('./s3_config.json');
var s3Bucket = new AWS.S3( { params: {Bucket: 'myBucket'} } );

在路由器方法中(ContentType应设置为镜像文件的内容类型):

var buf = Buffer.from(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('successfully uploaded the image!');
      }
  });

s3_config.json文件**:**

{
  "accessKeyId":"xxxxxxxxxxxxxxxx",
  "secretAccessKey":"xxxxxxxxxxxxxx",
  "region":"us-east-1"
}
ar7v8xwq

ar7v8xwq2#

下面是我看到的一篇文章中的代码,发布在下面:

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

uinbv5nw

uinbv5nw3#

好的,这一条是如何将画布数据保存到文件的答案
在我的代码中基本上是这样的

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)
fykwrbwg

fykwrbwg4#

接受的答案工作得很好,但如果有人需要接受任何文件而不仅仅是图像,那么这个regexp工作得很好:
/^data:.+;base64,/

dz6r00yl

dz6r00yl5#

对于Laravel开发者来说,这应该可以工作
$uploadFile是要上传到S3服务器的base64编码字符串。而$fileName应该包含文件扩展名,例如:filename.png。确保这对应于base64编码的data:image/{filetype}

/* upload the file  */
$path = Storage::putFileAs($uploadfolder, $uploadFile, $fileName, "s3");

请确保在调用此方法之前设置.env文件属性

相关问题