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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7511321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:32:58  来源:igfitidea点击:

Uploading base64 encoded Image to Amazon S3 via Node.js

javascriptnode.jsamazon-s3coffeescript

提问by Franz Enzenhofer

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.

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

what's the goal:

目标是什么:

  1. client sends a canvas datauri (png) to server (via socket.io)
  2. server uploads image to amazon s3
  1. 客户端将画布数据(png)发送到服务器(通过 socket.io)
  2. 服务器将图像上传到亚马逊 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/knoxseems 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.

欢迎任何想法、指示和反馈。

回答by Divyanshu Das

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 = 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 file is:-

s3_config.json 文件是:-

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

回答by Franz Enzenhofer

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)

回答by Harvey

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

回答by Ms01

The accepted answer works great but if someone needs to accept any file instead of just images this regexp works great:

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

/^data:.+;base64,/

/^data:.+;base64,/