Uploading base64 encoded image to Amazon S3 via Node.js

Yesterday I had a deep night coding session and created a small node.js / JS application (well, actually it’s CoffeeScript, but CoffeeScript is just JavaScript, so to speak, JS).

what purpose:

  1. the client sends the canvas data (png) to the server (via socket.io)
  2. server uploads image to Amazon S3

step 1 done.

the server now has a line a la

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

my question is: what are my next steps for streaming / uploading this data to Amazon S3 and creating a real image there?

knox https://github.com/LearnBoost/knox looks like a terrific library for PUT something in S3, but what I am missing is that between the string encoded in base64-code-image-string, and valid download action ?

Any ideas, pointers and reviews are welcome.

+77
javascript coffeescript amazon-s3
Sep 22 2018-11-11T00:
source share
4 answers

For people who are still struggling with this problem. 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'} } ); 

inside your router: - ContentType must be set to the content type of the image file

  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!'); } }); 
File

s3_config.json: -

 { "accessKeyId":"xxxxxxxxxxxxxxxx", "secretAccessKey":"xxxxxxxxxxxxxx", "region":"us-east-1" } 
+163
Sep 30 '14 at 2:00
source share

ok, this is the answer how to save the canvas data to a file

basically it looks like 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) 
+17
Sep 25 2018-11-11T00:
source share

The accepted answer works great, but if someone needs to accept any file instead of images, this regular expression works great:

/^data:.+;base64,/

+1
Jun 13 '19 at 10:10
source share

Replace not determined what steps to take

0
Jul 15 '19 at 14:42
source share



All Articles