Skip to content

Instantly share code, notes, and snippets.

@johnschimmel
Created November 14, 2013 15:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johnschimmel/7468267 to your computer and use it in GitHub Desktop.
Save johnschimmel/7468267 to your computer and use it in GitHub Desktop.
possibly code for saving data uri image to s3
var filename = 'my_data_pic.png';
var photoData = req.body.photoData;
// convert to buffer
var photo_buffer = new Buffer(b64str, 'base64');
// prepare database record
var photoPost = new Photo(); // create Blog object
// pick the Amazon S3 Bucket
var s3bucket = new AWS.S3({params: {Bucket: 'dwd_uploads'}});
// Set the bucket object properties
// Key == filename
// Body == contents of file
// ACL == Should it be public? Private?
// ContentType == MimeType of file ie. image/jpeg.
var params = {
Key: filename,
Body: photo_buffer,
ACL: 'public-read',
ContentType: mimeType
};
// Put the Object in the Bucket
s3bucket.putObject(params, function(err, data) {
if (err) {
console.log(err)
} else {
console.log("Successfully uploaded data to s3 bucket");
// add image to blog post
photoPost.image = filename;
}
photoPost.save();
res.redirect('/');
});
@npawar868
Copy link

npawar868 commented Sep 20, 2017

You can do this on front-end also by simply decoding the 64 bit data URI to original file content as follows

  1. Store your Data URI in a variable.

  2. Create function which decodes your data URI(64 bit encoded string) to string(Here I have created dataURItoBlob() function) and after 3 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.';`
    

You can send this decoded data to printer also.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment