【问题标题】:How to upload base64 encoded image data to S3 using JavaScript only?如何仅使用 JavaScript 将 base64 编码的图像数据上传到 S3?
【发布时间】:2012-10-04 17:35:50
【问题描述】:

我在 Heroku(雪松环境)上有一个 Rails 应用程序。它有一个页面,我在其中使用toDataURL() 方法将画布数据呈现为图像。我正在尝试使用 JavaScript(绕过服务器端)将返回的 base64 图像数据字符串直接上传到 s3。问题是,由于这不是文件,我如何将 base64 编码数据直接上传到 S3 并将其另存为文件?

【问题讨论】:

    标签: javascript heroku canvas amazon-s3 base64


    【解决方案1】:

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

    您必须将数据 URI 转换为 blob,然后使用 CORS 将该文件上传到 S3,如果您正在处理多个文件,我对每个文件都有单独的 XHR 请求。

    我发现这个函数可以将你的数据 URI 变成一个 blob,然后可以使用 CORS (Convert Data URI to 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.

    【讨论】:

      【解决方案2】:

      Jamcoope 的回答非常好,但是并非所有浏览器都支持 blob 构造函数。最值得注意的是 android 4.1 和 android 4.3。有 Blob polyfill,但 xhr.send(...) 不适用于 polyfill。最好的选择是这样的:

      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】:

        如果有人关心:这是上面给出的函数的咖啡脚本版本!

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

        【讨论】:

          【解决方案4】:

          不确定 OP 是否已经解决了这个问题,但我正在开发一个非常相似的功能。在做一些研究时,我发现了这些可能会有所帮助的文章。

          【讨论】:

            猜你喜欢
            • 2015-09-05
            • 2014-06-26
            • 2011-11-22
            • 2014-06-27
            • 2016-04-13
            • 2022-01-11
            • 2020-09-03
            • 2013-08-27
            • 2016-10-23
            相关资源
            最近更新 更多