Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

upload canvas data to s3

Now since the amazon has enabled CORS I was wondering if this is possible.

Can the html canvas data (on client browser) be converted to a something and uploaded to s3 directly ?

I am sure I can make a PUT request to amazon but that requires a File .

I can get base64 encoded image data or even a Blob but is there a way to save this as an image to S3 from the client browser ?

Is there a way to convert canvas to File so that I can make a PUT request or a way that amazon understands Blob and saves it as an image ?

like image 368
Gaurav Shah Avatar asked Dec 21 '12 12:12

Gaurav Shah


4 Answers

Here is a working example where you take a data URL from a canvas and upload it to S3:

var dataUrl = canvas.toDataURL("image/jpeg");
var blobData = dataURItoBlob(dataUrl);
var params = {Key: "file_name", ContentType: "image/jpeg", Body: blobData};
bucket.upload(params, function (err, data) {});

dataURItoBlob:

function dataURItoBlob(dataURI) {
    var binary = atob(dataURI.split(',')[1]);
    var array = [];
    for(var i = 0; i < binary.length; i++) {
        array.push(binary.charCodeAt(i));
    }
    return new Blob([new Uint8Array(array)], {type: 'image/jpeg'});
}
like image 84
rahil sharma Avatar answered Nov 03 '22 22:11

rahil sharma


There is an old post method to upload data from browser to s3

http://s3.amazonaws.com/doc/s3-example-code/post/post_sample.html

then I have used this idea Convert Data URI to File then append to FormData

and instead of normal POST there can be an xhr request with the formdata to amazon and you are done

like image 3
Gaurav Shah Avatar answered Nov 03 '22 21:11

Gaurav Shah


I was researching this and not having much luck until I found this post: https://github.com/aws/aws-sdk-js/issues/1712#issuecomment-329542614

AWS has a utility that will decode base64 in their aws-sdk: AWS.util.base64.decode(image)

Simple solution, and worked for me.

like image 1
Dave Hilson Avatar answered Nov 03 '22 21:11

Dave Hilson


Using toBlob:

canvas.toBlob((blob) => {
  if (blob === null) return;
  bucket.upload({
    Key: "where/the/file/goes.jpg"
    ContentType: "image/jpeg",
    Body: blob,
  }, (err, data) => {});
}, "image/jpeg");
like image 1
Overcode Avatar answered Nov 03 '22 20:11

Overcode