简体   繁体   English

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

[英]Uploading base64 encoded Image to Amazon S3 via Node.js

Yesterday I did a deep night coding session and created a small node.js/JS (well actually CoffeeScript, but CoffeeScript is just JavaScript so lets say JS) app. Yesterday I did a deep night coding session and created a small node.js/JS (well actually CoffeeScript, but CoffeeScript is just JavaScript so lets say JS) app.

what's the goal:目标是什么:

  1. client sends a canvas datauri (png) to server (via socket.io)客户端将 canvas datauri (png) 发送到服务器(通过 socket.io)
  2. server uploads image to amazon s3服务器将图像上传到亚马逊 s3

step 1 is done.步骤 1 完成。

the server now has a string a la服务器现在有一个字符串 a la

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

my question is: what are my next steps to "stream"/upload this data to Amazon S3 and create an actual image there?我的问题是:我下一步要“流式传输”/将此数据上传到 Amazon S3 并在那里创建实际图像是什么?

knox https://github.com/LearnBoost/knox seems like an awesome lib to PUT something to S3, but what I'm missing is the glue between the base64-encoded-image-string and actual upload action ? knox https://github.com/LearnBoost/knox似乎是一个很棒的库,可以将一些东西放到 S3 中,但我缺少的是 base64-encoded-image-string 和实际上传操作之间的粘合剂

Any ideas, pointers and feedback welcome.欢迎任何想法,指针和反馈。

For people who are still struggling with this issue.对于仍在为这个问题而苦苦挣扎的人。 Here is the approach I used with native aws-sdk:这是我在原生 aws-sdk 中使用的方法:

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

Inside your router method (ContentType should be set to the content type of the image file):在路由器方法中(ContentType 应设置为图像文件的内容类型):

  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 file: s3_config.json 文件:

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

ok, this one is the answer how to save canvas data to file好的,这是如何将画布数据保存到文件的答案

basically it loos like this in my code基本上它在我的代码中是这样的

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)

Here's the code from one article I came across, posting below:这是我遇到的一篇文章中的代码,贴在下面:

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;

Read more: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property阅读更多: http : //docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html#upload-property

Credits: https://medium.com/@mayneweb/upload-a-base64-image-data-from-nodejs-to-aws-s3-bucket-6c1bd945420f学分: https : //medium.com/@mayneweb/upload-a-base64-image-data-from-nodejs-to-aws-s3-bucket-6c1bd945420f

接受的答案效果很好,但如果有人需要接受任何文件而不仅仅是图像,则此正则表达式效果很好:

/^data:.+;base64,/

For laravel developers this should work对于 laravel 开发人员,这应该可以工作


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

make sure to set your.env file property before calling this method确保在调用此方法之前设置 your.env 文件属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM