Using HTML5/JavaScript to generate and save a file
This code snippet initiates download of 'example.txt' containing 'Hello, world!'.
Creating downlodable links
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.
Was this article helpful?