通过 Node.js 将 base64 编码的图像上传到 Amazon S3 [英] Uploading base64 encoded Image to Amazon S3 via Node.js

查看:41
本文介绍了通过 Node.js 将 base64 编码的图像上传到 Amazon S3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

昨天我做了一个深夜编码会议并创建了一个小的 node.js/JS(实际上是 CoffeeScript,但 CoffeeScript 只是 JavaScript,所以可以说是 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.

目标是什么:

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

第一步完成.

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

the server now has a string a la

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

我的问题是:我下一步将这些数据流式传输"/上传到 Amazon S3 并在那里创建实际图像是什么?

knox https://github.com/LearnBoost/knox 似乎是一个很棒的库来放置一些东西到 S3,但我缺少的是 base64 编码图像字符串和实际上传操作之间的胶水?

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?

欢迎提出任何想法、建议和反馈.

Any ideas, pointers and feedback welcome.

推荐答案

适用于仍在为此问题苦苦挣扎的人.这是我在原生 aws-sdk 中使用的方法:

For people who are still struggling with this issue. Here is the approach I used with native aws-sdk:

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

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

Inside your router method (ContentType should be set to the content type of the image file):

  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 文件:

s3_config.json file:

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

这篇关于通过 Node.js 将 base64 编码的图像上传到 Amazon S3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆