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

昨天我做了一个深夜编码会话,并创建了一个小节点.js / JS(实际上是CoffeeScript,但CoffeeScript只是JavaScript,所以让我们说JS)应用程序。

目标是什么:

  1. 客户端将画布数据(png)发送到服务器(通过 socket.io)
  2. 服务器将图像上传到 Amazon s3

步骤 1 已完成。

服务器现在有一个字符串 a la

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

我的问题是:我下一步要“流式传输”/上传此数据到Amazon S3并在那里创建实际图像?

knox https://github.com/LearnBoost/knox 似乎是一个很棒的lib,可以将某些东西放到S3上,但是我缺少的是base64编码的图像字符串和实际上传操作之间的粘合剂

欢迎任何想法,指针和反馈。


答案 1

对于那些仍在为这个问题而苦苦挣扎的人。以下是我与原生 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"
}

答案 2

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

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