Home

Awesome

download

NPM version Size License CDNJS

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 URL, 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.

Getting and Using


Via NPM/Bower

npm install downloadjs <br /> bower install downloadjs

require("downloadjs")(data, strFileName, strMimeType);

Simple global download function via <script> include

download(data, strFileName, strMimeType);

Included via AMD

require(['path/to/file'], function(download) {
    download(data, strFileName, strMimeType);
});

Parameters


Example Usage


Plain Text

text string - live demo

download("hello world", "dlText.txt", "text/plain");

text dataURL - live demo

download("data:text/plain,hello%20world", "dlDataUrlText.txt", "text/plain");

text blob - live demo

download(new Blob(["hello world"]), "dlTextBlob.txt", "text/plain");

text url - live demo

download("/robots.txt");

text UInt8 Array - live demo

var str= "hello world",	arr= new Uint8Array(str.length);
str.split("").forEach(function(a,b){
  arr[b]=a.charCodeAt();
});

download( arr, "textUInt8Array.txt", "text/plain" );

HTML

html string - live demo

download(document.documentElement.outerHTML, "dlHTML.html", "text/html");

html Blob - live demo

download(new Blob(["hello world".bold()]), "dlHtmlBlob.html", "text/html");

ajax callback - live demo

(note that callback mode won't work on vanilla ajax or with binary files)

$.ajax({
		url: "/download.html",
		success: download.bind(true, "text/html", "dlAjaxCallback.html")
});

Binary Files

image from URL - live demo

download("/diff6.png");

Image via ajax for custom filename - live demo

var x=new XMLHttpRequest();
x.open( "GET", "/diff6.png" , true);
x.responseType="blob";
x.onload= function(e){download(e.target.response, "awesomesauce.png", "image/png");};
x.send();

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:

FAQ


Change Log (v4.1)