3
votes

Right now, I've passed the canvas data URI string

(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAUAAAADwCAYAAABxLb1rAAAgAElEQVR..... )

to my hapi (NodeJS) server.

My question is:

What are my next steps to "stream"/upload this data to Amazon S3 and create an actual image there?

2
So the real question is, how do you upload from nodejs to amazon S3. - Sean_A91
You need to create a stream from this base64 image and upload the stream to S3 - Vsevolod Goloviznin
If when you search SO already you find stackoverflow.com/questions/7511321/… and stackoverflow.com/questions/5867534/… ? Let me guess you did not even search. - Darryl Miles

2 Answers

0
votes

before send object to s3 you must transform base64 to buffer and after send, for example:

var buf = new Buffer(b64string, 'base64');
s3.putObject({/*some  params*/, Body: buf}, function(err, data) {
  if (err) console.log(err, err.stack); // an error occurred
  else     console.log(data);           // successful response
});

After this you send data to s3 and you will can open image without decode.

Good luck!

0
votes
  1. Store your Data URI in a vaiable.
  2. Create function which decodes your data URI(64 bit encoded string) to string(Here I have created dataURItoBlob() function) and after decoding return the string
  3. Pass that string to in body of S3 upload function

    var myDataUri = "data:application/pdf;base64,JVBERi0xLjMKMyAwIG9iago8PC9UeXBlIC9QYW..."
    
    var myFile=dataURItoBlob(myDataUri);
    
    function dataURItoBlob(dataURI) {
       console.log('1: ',dataURI);
       var binary = atob(dataURI.split(',')[1]);
       var array = [];
       console.log('2: ',binary.length);
       for (var i = 0; i < binary.length; i++) {
          array.push(binary.charCodeAt(i));
       }
      return new Blob([new Uint8Array(array)], {
      type: 'application/pdf'
      });
    }
    
     if (myFile)) {
       results.innerHTML = '';
       var params = {
         Key: new Date().getTime() + '.pdf',
         ContentType: 'application/pdf',
         Body: myFile
       };
    
      bucket.upload(params, function(err, data) {
        results.innerHTML = err ? 'ERROR!' : 'UPLOADED.: ' + file;
      });
     } else {
     results.innerHTML = 'Nothing to upload.';
    }