4

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?

Rodmentou
  • 1,610
  • 3
  • 21
  • 39
Kim Tim
  • 51
  • 1
  • 5
  • So the real question is, how do you upload from nodejs to amazon S3. – Sean_A91 Nov 18 '15 at 12:15
  • You need to create a stream from this base64 image and upload the stream to S3 – Vsevolod Goloviznin Nov 18 '15 at 12:23
  • 5
    If when you search SO already you find http://stackoverflow.com/questions/7511321/uploading-base64-encoded-image-to-amazon-s3-via-node-js?rq=1 and http://stackoverflow.com/questions/5867534/how-to-save-canvas-data-to-file/5971674#5971674 ? Let me guess you did not even search. – Darryl Miles Nov 18 '15 at 12:38

2 Answers2

1

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!

siavolt
  • 6,869
  • 5
  • 24
  • 27
1
  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.';
    }
    
Nilesh Pawar
  • 655
  • 7
  • 12