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

问题描述 投票:14回答:4

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

javascript heroku canvas amazon-s3 base64
4个回答
26
投票

我已经找到一种方法来做到这一点。很多搜索后一看不同的教程。

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

我发现这个功能,将你的数据URI成可随后直接使用CORS被上传到S3斑点(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 is a great tutorial on uploading directly to S3, you will need to customise the code to allow for the blob instead of files.


5
投票

Jamcoope的答案是非常好的,但是斑构造并非所有浏览器都支持。最值得注意的是安卓4.1和安卓4.3。有Blob polyfills,但xhr.send(...)不会与填充工具的工作。最好的办法是这样的:

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

3
投票

如果有人关心:这里是上面给出的函数的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'}

1
投票

不知道OP已经解决了这一点,但我工作在一个非常类似的功能。在做了一些研究,我碰到这些文章可能会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.