The HTML5 `<a>` tag can use the `download` attribute to set the download of a resource, but it must be same-origin. If the browser can parse it, it will open directly.

In this case, we can use the third-party library download to implement more complete download functionality.

download.js related resources:

The download.js library provides a `download()` function for downloading files.

The download content can be a URL, string, Blob, or typed data array, or a dataURL that represents the file data as a base64 or URL-encoded string.

Regardless of the input format, `download()` uses the specified file name and MIME information to save the file in the same way as a server using the Content-Disposition HTTP header.

download(data, strFileName, strMimeType);
  • data - The data content to download, can be Blob, File, String, or dataURL.
  • strFileName - The name of the file to be created.
  • strMimeType - The MIME content type of the file to download.

Examples

Text

Store the string into a dlText.txt file and download it:

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

dataURL text example:

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

blob text example:

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

url example:

download("/robots.txt");

UInt8 text array example:

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 example:
download(document.documentElement.outerHTML, "dlHTML.html", "text/html");

html Blob example:

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

ajax callback example:

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

Binary files

Image URL:

download("/diff6.png");

Asynchronously download image:

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();