Skip to content

Instantly share code, notes, and snippets.

@nolanlawson
Last active February 20, 2017 17:34
Show Gist options
  • Save nolanlawson/10340255 to your computer and use it in GitHub Desktop.
Save nolanlawson/10340255 to your computer and use it in GitHub Desktop.
HTML5 Blob shim

HTML5 Blob shim

Small JavaScript function that abstracts constructing a Blob object, so it works in older browsers that don't support the native Blob constructor (e.g. old versions of QtWebKit).

Usage

The function createBlob() simply replaces new Blob():

var blob = createBlob(['check out my regular old text blob']);

And here's some application/json data for variety:

var blob = createBlob([atob('eyJIZWxsbyI6IndvcmxkIn0=')], {type : 'application/json'});

And now we get really fancy:

var blob = createBlob([atob('iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAMFBMVEX+9+' +
                'j+9OD+7tL95rr93qT80YD7x2L6vkn6syz5qRT4ogT4nwD4ngD4nQD4nQD4' +
                'nQDT2nT/AAAAcElEQVQY002OUQLEQARDw1D14f7X3TCdbfPnhQTqI5UqvG' +
                'OWIz8gAIXFH9zmC63XRyTsOsCWk2A9Ga7wCXlA9m2S6G4JlVwQkpw/Ymxr' +
                'UgNoMoyxBwSMH/WnAzy5cnfLFu+dK2l5gMvuPGLGJd1/9AOiBQiEgkzOpg' +
                'AAAABJRU5ErkJggg==')], {type : 'image/png'});

More info

This is the same shim used in PouchDB. I didn't write it.

You can also read all about Blob or the deprecated BlobBuilder API.

function createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (e) {
if (e.name !== "TypeError") {
throw e;
}
var BlobBuilder = window.BlobBuilder ||
window.MSBlobBuilder ||
window.MozBlobBuilder ||
window.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment