来自DataURL的Blob?

Sha*_*way 73 javascript fileapi

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

dev*_*l69 123

用户Matt一年前提出了以下代码(如何将dataURL转换为javascript中的文件对象?)这可能对您有所帮助

编辑:正如一些评论者报道的那样,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;

}
Run Code Online (Sandbox Code Playgroud)

  • 您可以替换BlobBuilder而不是blob.var blob = new Blob([ab],{type:mimeString}); 返回blob; (8认同)
  • Blob the Builder?:) (8认同)
  • 重复的分裂看起来有点浪费,因为这可能是一个非常大的字符串. (4认同)
  • 注意:[根据MDN](https://developer.mozilla.org/en-US/docs/Web/API/BlobBuilder),现在不推荐使用BlobBuilder.不知道从什么时候开始.(我知道这是一个很老的问题和答案,只是让它保持最新.)而不是[Blob](https://developer.mozilla.org/en-US/docs/Web/API/ Blob)接受一个部件数组作为其构造函数的第一个参数. (2认同)
  • 变量"ia"的作用是什么 - 它赋予了一个值但从未用于形成blob.为什么? (2认同)

End*_*ess 29

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

警告:可能违反内容安全策略(CSP)
...如果您使用该内容

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

fetch(url)
.then(res => res.blob())
.then(blob => console.log(blob))
Run Code Online (Sandbox Code Playgroud)

如果不使用lib,不要认为你可以做得更小

  • 异步版本:`const blob = await(等待获取(url)).blob();` (8认同)
  • edge 14 和 safari 10.1 支持它 (2认同)
  • 这个“fetch”的更大问题是它强制使用异步 API。 (2认同)

Jan*_*erk 21

现代浏览器中,您可以使用 Christian d'Heureuse 在评论中建议的 one liner:

const blob = await (await fetch(dataURI)).blob(); 
Run Code Online (Sandbox Code Playgroud)

  • 使用此方法的一个警告是,这可能会违反您的内容安全策略 (CSP)(如果您的应用程序有任何内容安全策略)。 (2认同)

小智 17

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});
    }
Run Code Online (Sandbox Code Playgroud)

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


Adr*_*ria 11

基于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 );
});
Run Code Online (Sandbox Code Playgroud)


HaN*_*riX 5

尝试:

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
    });
}
Run Code Online (Sandbox Code Playgroud)


B T*_*B T 5

由于这些答案都不支持 Base64 和非 Base64 dataURL,因此以下答案基于 vuamitom 已删除的答案:

// from /sf/ask/2599479221/
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})
    }
}
Run Code Online (Sandbox Code Playgroud)

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