download.js

Client-side file downloading using JS and HTML5

Summary

The download() function is used to trigger a file download from JavaScript. It specifies the contents and name of a new file placed in the browser's download directory. The input can be a String, Blob, or Typed Array of data, or via a dataURL representing the file's data as base64 or url-encoded string. No matter the input format, download() saves a file using the specified file name and mime information in the same manner as a server using a Content-Disposition HTTP header.

Syntax

download(data, strFileName, strMimeType);

Parameters

data
The Blob, File, String, or dataURL containing the soon-to-ba File's contents.
strFileName
The name of the file to be created. Note that older browsers (like FF3.5, Ch5) don't honor the file name you provide, instead they automatically name the downloaded file.
strMimeType
The MIME content-type of the file to download. While optional, it helps the browser present friendlier information about the download to the user, encouraging them to accept the download.

Compatibility

download.js works with a wide range of devices and browsers.

You can expect it to work for the vast majority of your users, with some common-sense limits:

Download

The 3kb script is available to download or view online or Fork on GitHub

Change Log (v3)

  1. 2008 :: landed a FF+Chrome compat way of downloading strings to local un-named files, upgraded to use a hidden frame and optional mime
  2. 2012 :: added named files via a[download], msSaveBlob() for IE (10+) support, and window.URL support for larger+faster saves than dataURLs
  3. 2014 :: added dataURL and Blob Input, bind-toggle arity, and legacy dataURL fallback was improved with force-download mime and base64 support
  4. 20XX :: ???? Considering Zip, Tar, and other multi-file outputs, Blob.prototype.download option, and more, stay tuned folks.

Test Usages

Plain Text

HTML

Binary

Full Source

Creative Commons License This work is licensed under a Creative Commons Attribution 4.0 International License, attribute to "dandavis".