Explain Codes LogoExplain Codes Logo

Using HTML5/JavaScript to generate and save a file

html
data-uri
blob
file-saver-js
Alex KataevbyAlex Kataev·Jan 1, 2025
TLDR
Use JavaScript to create a **Blob** for your data, then trigger download using a link. ```javascript var blob = new Blob(['Hello, world!'], { type: 'text/plain' }); var url = URL.createObjectURL(blob); var a = document.createElement('a'); a.href = url; a.download = 'example.txt'; document.body.appendChild(a); // Append the link first, our new "child". a.click(); // This is like asking the new "child" to do their first task. document.body.removeChild(a); // Remove the link after click, like covering our tracks.

This code snippet initiates download of 'example.txt' containing 'Hello, world!'.

Get rid of Flash and server-side download prompts. Instead, use data URIs and anchor (<a>) tags with the download attribute to insure immediate file download.

Understanding Data URI

Browsers have restrictions on data URI length. Voluminous blobs bomb blasts, causing failed downloads. Mitigate this using encodeURIComponent and Base64 encoding, especially for binary data.

Triggering downloads

To prompt a download without involving server, you can open a data URI in a new window, but a guaranteed approach is using URL.createObjectURL in tandem with Blob or File objects.

Compatibility

Where support for a.download is scarce or peculiar APIs like IE's navigator.msSaveBlob are dominant, consider FileSaver.js for cross-browser compatibility.

Safety First

Security is non-negotiable: sanitize filenames against injection attacks, and be deliberate with blob MIME-types guiding browser handling of downloaded file.

Advanced methods

While the basic scenario suffices for many use cases, let's dive into some quirks and features that could revolutionize your file generation and download process.

Seamless downloads

For a sophisticated user experience, consider programmatic download triggers. document.createEvent can simulate user actions like clicks, but do note that its behavior varies across different browsers.

Handling different file types

Different MIME-types for Blobs guide different browser actions upon download. Whether dealing with a PDF, image, or text file, specifying the correct MIME-type ensures appropriate file handling.

Advanced scenarios

Offers unique perspectives and solutions to convoluted download situations.

Dynamic content

Applications allowing users to generate content can dynamically craft the Blob.

Exporting user data

To export data, such as progress or configurations, extract a serialized version of the data (like JSON), convert it into a Blob, and present as a downloadable file.

Generating media files

Create an image, audio, and other media files on the client-side, using canvas for images or the Web Audio API for sound, and package these as downloadable files.

File types and extensions

Preserving file extensions in the download attribute ensures the downloaded file works as expected.