Javascript 来自 DataURL 的 Blob?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12168909/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:18:05  来源:igfitidea点击:

Blob from DataURL?

javascriptfileapi

提问by Shane Holloway

Using FileReader's readAsDataURL()I can transform arbitrary data into a Data URL. Is there way to convert a Data URL back into a Blobinstance using builtin browser apis?

使用FileReader's readAsDataURL()I 可以将任意数据转换为数据 URL。有没有办法Blob使用内置浏览器 api将数据 URL 转换回实例?

回答by devnull69

User Matt has proposed the following code a year ago ( How to convert dataURL to file object in javascript?) which might help you

用户 Matt 在一年前提出了以下代码(How to convert dataURL to file object in javascript?)这可能对您有所帮助

EDIT: As some commenters reported, BlobBuilder has been deprecated some time ago. This is the updated code:

编辑:正如一些评论者所报告的那样,BlobBuilder 前段时间已被弃用。这是更新后的代码:

function dataURItoBlob(dataURI) {
  // convert base64 to raw binary data held in a string
  // doesn't handle URLEncoded DataURIs - see SO answer #6850276 for code that does this
  var byteString = atob(dataURI.split(',')[1]);

  // separate out the mime component
  var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]

  // write the bytes of the string to an ArrayBuffer
  var ab = new ArrayBuffer(byteString.length);

  // create a view into the buffer
  var ia = new Uint8Array(ab);

  // set the bytes of the buffer to the correct values
  for (var i = 0; i < byteString.length; i++) {
      ia[i] = byteString.charCodeAt(i);
  }

  // write the ArrayBuffer to a blob, and you're done
  var blob = new Blob([ab], {type: mimeString});
  return blob;

}

回答by Endless

Like @Adria method but with Fetch api and just smaller [caniuse?]
Don't have to think about mimetype since blob response type just works out of the box

像@Adria 方法,但使用 Fetch api 并且更小 [ caniuse? ]
不必考虑 mimetype,因为 blob 响应类型是开箱即用的

Warning: Can violate the Content Security Policy (CSP)
...if you use that stuff

警告:可能违反内容安全政策 (CSP)
...如果你使用那些东西

var url = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="

fetch(url)
.then(res => res.blob())
.then(blob => console.log(blob))

Don't think you could do it any smaller then this without using lib's

不要认为你可以在不使用 lib 的情况下做得更小

回答by Shawn Wu

dataURItoBlob : function(dataURI, dataTYPE) {
        var binary = atob(dataURI.split(',')[1]), array = [];
        for(var i = 0; i < binary.length; i++) array.push(binary.charCodeAt(i));
        return new Blob([new Uint8Array(array)], {type: dataTYPE});
    }

input dataURI is Data URL and dataTYPE is the file type and then output blob object

输入 dataURI 是数据 URL 和 dataTYPE 是文件类型然后输出 blob 对象

回答by Adria

XHR based method.

基于 XHR 的方法。

function dataURLtoBlob( dataUrl, callback )
{
    var req = new XMLHttpRequest;

    req.open( 'GET', dataUrl );
    req.responseType = 'arraybuffer'; // Can't use blob directly because of https://crbug.com/412752

    req.onload = function fileLoaded(e)
    {
        // If you require the blob to have correct mime type
        var mime = this.getResponseHeader('content-type');

        callback( new Blob([this.response], {type:mime}) );
    };

    req.send();
}

dataURLtoBlob( 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==', function( blob )
{
    console.log( blob );
});

回答by HaNdTriX

try:

尝试:

function dataURItoBlob(dataURI) {
    if(typeof dataURI !== 'string'){
        throw new Error('Invalid argument: dataURI must be a string');
    }
    dataURI = dataURI.split(',');
    var type = dataURI[0].split(':')[1].split(';')[0],
        byteString = atob(dataURI[1]),
        byteStringLength = byteString.length,
        arrayBuffer = new ArrayBuffer(byteStringLength),
        intArray = new Uint8Array(arrayBuffer);
    for (var i = 0; i < byteStringLength; i++) {
        intArray[i] = byteString.charCodeAt(i);
    }
    return new Blob([intArray], {
        type: type
    });
}

回答by georgeawg

Create a blob using XHR API:

使用XHR API创建一个 blob :

function dataURLtoBlob( dataUrl, callback )
{
    var req = new XMLHttpRequest;

    req.open( 'GET', dataUrl );
    req.responseType = 'blob';

    req.onload = function fileLoaded(e)
    {
        callback(this.response);
    };

    req.send();
}

var dataURI = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='

dataURLtoBlob(dataURI , function( blob )
{
    console.log( blob );
});

回答by cuixiping

Use my code convert dataURI to blob. It's simpler and cleaner than others.

使用我的代码将 dataURI 转换为 blob。它比其他人更简单、更干净。

function dataURItoBlob(dataURI) {
    var arr = dataURI.split(','), mime = arr[0].match(/:(.*?);/)[1];
    return new Blob([atob(arr[1])], {type:mime});
}

回答by B T

Since none of these answers support base64 and non-base64 dataURLs, here's one that does based on vuamitom's deleted answer:

由于这些答案都不支持 base64 和非 base64 dataURL,因此这里有一个基于 vuamitom 已删除的答案:

// from https://stackoverflow.com/questions/37135417/download-canvas-as-png-in-fabric-js-giving-network-error/
var dataURLtoBlob = exports.dataURLtoBlob = function(dataurl) {
    var parts = dataurl.split(','), mime = parts[0].match(/:(.*?);/)[1]
    if(parts[0].indexOf('base64') !== -1) {
        var bstr = atob(parts[1]), n = bstr.length, u8arr = new Uint8Array(n)
        while(n--){
            u8arr[n] = bstr.charCodeAt(n)
        }

        return new Blob([u8arr], {type:mime})
    } else {
        var raw = decodeURIComponent(parts[1])
        return new Blob([raw], {type: mime})
    }
}

Note: I'm not sure if there are otherdataURL mime types that might have to be handled differently. But please let me know if you find out! Its possible that dataURLs can simply have any format they want, and in that case it'd be up to you to find the right code for your particular use case.

注意:我不确定是否还有其他dataURL mime 类型可能需要以不同的方式处理。但是如果你发现了,请告诉我!dataURLs 可能只是他们想要的任何格式,在这种情况下,您可以为您的特定用例找到正确的代码。

回答by 3on

use

FileReader.readAsArrayBuffer(Blob|File)

rather than

而不是

FileReader.readAsDataURL(Blob|File)