如何上传的base64 EN codeD映像数据只使用JavaScript S3?映像、上传、数据、codeD

2023-09-11 08:50:49 作者:唱征服i

我在Heroku(雪松ENV)一个Rails应用程序。它有一个网页,我呈现在画布上的数据到图像使用 toDataURL()方法。我想直接上传返回的base64图像数据字符串使用JavaScript(绕过服务器端)到S3。问题是,因为这不是一个文件,我怎么上传的base64 EN codeD数据直接S3并保存为一个文件呢?

I have a rails app on Heroku (cedar env). It has a page where I render the canvas data into an image using toDataURL() method. I'm trying to upload the returned base64 image data string directly to s3 using JavaScript (bypassing the server-side). The problem is that since this isn't a file, how do I upload the base64 encoded data directly to S3 and save it as a file there?

推荐答案

我已经找到一种方法来做到这一点。经过大量的搜索一看不同的教程。

I have found a way to do this. After a lot of searching a looking at different tutorials.

您必须将数据URI转换为一个blob,然后上传文件使用CORS至S3,如果你正在使用多个文件,我为每个单独的XHR请求。

You have to convert the Data URI to a blob and then upload that file to S3 using CORS, if you are working with multiple files I have separate XHR requests for each.

我发现这个功能,将你的数据URI成,然后可以上传到S3直接用CORS(转换数据URI一个blob到BLOB )

I found this function which turns your the Data URI into a blob which can then be uploaded to S3 directly using CORS (Convert Data URI to Blob )

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

Here是一个伟大的教程直接上传到S3,您将需要自定义code以允许BLOB,而不是文件。