Code Snippets
/

Trigger a File Download from a Blob

Trigger a File Download from a Blob

Generating a CSV, JSON export, or screenshot client-side and saving it without a server round-trip is a five-line trick: build a `Blob`, mint an object URL, click a hidden `<a download>`, and revoke the URL. This snippet covers the canonical helper, a JSON export wrapper, and the cleanup pattern that prevents memory leaks during long-running sessions.

JavaScript
Medium
3 snippets
js-web-apis
js-dom
utility
blob-storage

699 views

16

function downloadBlob(blob, filename) {
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

const blob = new Blob(['hello, world'], { type: 'text/plain' });
downloadBlob(blob, 'hello.txt');
console.log('download triggered');

URL.createObjectURL(blob) mints a blob:... URL that points at the in-memory data and can be assigned to any URL-accepting attribute. Programmatic .click() on a hidden <a> with the download attribute is the only cross-browser way to trigger a save dialog from JS. Inserting the anchor into the DOM is required in some browsers (Firefox in particular); pulling it back out keeps the page tree clean. Calling URL.revokeObjectURL immediately after the click frees the underlying blob reference so the GC can reclaim memory.