Skip to content

Instantly share code, notes, and snippets.

@MohammadYounes
Forked from fupslot/gist:5015897
Last active August 29, 2015 14:21
Show Gist options
  • Save MohammadYounes/9def2b27db9c8424666b to your computer and use it in GitHub Desktop.
Save MohammadYounes/9def2b27db9c8424666b to your computer and use it in GitHub Desktop.
function dataURItoBlob(dataURI, callback) {
// 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);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i++) {
ia[i] = byteString.charCodeAt(i);
}
// write the ArrayBuffer to a blob, and you're done
var bb = new BlobBuilder();
bb.append(ab);
return bb.getBlob(mimeString);
}
@MohammadYounes
Copy link
Author

http://updates.html5rocks.com/2012/06/Don-t-Build-Blobs-Construct-Them

BlobBuilder():

window.BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder ||
                     window.MozBlobBuilder || window.MSBlobBuilder;
window.URL = window.URL || window.webkitURL;

var bb = new BlobBuilder();
bb.append('body { color: red; }');
var blob = bb.getBlob('text/css');

var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = window.URL.createObjectURL(blob);

document.body.appendChild(link);

Blob():

window.URL = window.URL || window.webkitURL;

var blob = new Blob(['body { color: red; }'], {type: 'text/css'});

var link = document.createElement('link');
link.rel = 'stylesheet';
link.href = window.URL.createObjectURL(blob);
document.body.appendChild(link);

Handy! So now, instead of appending to a BlobBuilder, we can simply create the Blob from an array of data parts. The data parts can be different types (DOMString, ArrayBuffer, Blob) and in any order. For example:

var blob = new Blob(['1234567890', blob, arrayBuffer]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment