简体   繁体   English

如何仅使用 JavaScript 将 base64 编码的图像数据上传到 S3?

[英]How to upload base64 encoded image data to S3 using JavaScript only?

I have a rails app on Heroku (cedar env).我在 Heroku (cedar env) 上有一个 rails 应用程序。 It has a page where I render the canvas data into an image using toDataURL() method.它有一个页面,我在其中使用toDataURL()方法将画布数据渲染为图像。 I'm trying to upload the returned base64 image data string directly to s3 using JavaScript (bypassing the server-side).我正在尝试使用 JavaScript(绕过服务器端)将返回的 base64 图像数据字符串直接上传到 s3。 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?问题是,由于这不是文件,如何将 base64 编码数据直接上传到 S3 并将其另存为文件?

I have found a way to do this.我找到了一种方法来做到这一点。 After a lot of searching a looking at different tutorials.经过大量搜索,查看了不同的教程。

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 转换为 blob,然后使用 CORS 将该文件上传到 S3,如果您正在处理多个文件,我对每个文件都有单独的 XHR 请求。

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 )我发现这个函数可以将您的数据 URI 转换为 blob,然后可以使用 CORS(将数据 URI 转换为 Blob )直接上传到 S3

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 is a great tutorial on uploading directly to S3, you will need to customise the code to allow for the blob instead of files. 这是一个关于直接上传到 S3 的很棒的教程,您需要自定义代码以允许使用 blob 而不是文件。

Jamcoope's answer is very good, however the blob constructor is not supported by all browsers. Jamcoope 的回答非常好,但是并非所有浏览器都支持 blob 构造函数。 Most notably android 4.1 and android 4.3.最值得注意的是 android 4.1 和 android 4.3。 There are Blob polyfills, but xhr.send(...) will not work with the polyfill.Blob xhr.send(...) ,但xhr.send(...)不适xhr.send(...) The best bet is something like this:最好的选择是这样的:

var u = dataURI.split(',')[1],
    binary = atob(u),
    array = [];

for (var i = 0; i < binary.length; i++) {
    array.push(binary.charCodeAt(i));
}

var typedArray = Uint8Array(array);

// now typedArray.buffer can be passed to xhr.send

If anyone cares: here is the coffescript version of the function given above!如果有人关心:这是上面给出的函数的 coffescript 版本!

  convertToBlob = (base64) ->
    binary = atob base64.split(',')[1]
    array = []
    for i in [0...binary.length]
      array.push binary.charCodeAt i
    new Blob [new Uint8Array array], {type: 'image/jpeg'}

Not sure if OP has already solved this, but I'm working on a very similar feature.不确定 OP 是否已经解决了这个问题,但我正在研究一个非常相似的功能。 In doing a little research, I came across these articles that might be helpful.在做一些研究时,我发现了这些可能有帮助的文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM