upload canvas data to s3

2019-02-01 23:53发布

问题:

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 ?

回答1:

This is what worked for me :

var canvas  = document.getElementById("imagePreviewChatFooter");
                    var dataUrl = canvas.toDataURL("image/jpeg");
                    var blobData = dataURItoBlob(dataUrl);
                    var fileName = file.name;
                    var params = {Key: fileName, ContentType: file.type, Body: blobData};
                    bucket.upload(params, function (err, data) {
                        console.log(data);
                        console.log(err ? 'ERROR!' : 'UPLOADED.');
                    });

AND

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


回答2:

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



回答3:

The easiest way to save canvas is to convert it to base64:

canvas.toDataURL();

or you can set image type via argument:

canvas.toDataURL("image/png");
canvas.toDataURL("image/jpeg");
// etc

Also watch this lib: http://www.nihilogic.dk/labs/canvas2image/