Using the JS download Library to Download Resources
Category Programming Technology
The HTML5 a tag can use the download attribute to set the resource download, but it needs to be same-origin, and if the browser can parse it, it will open directly.
In this case, we can use the third-party library download to achieve more complete download functionality.
download.js related resources:
Github address: https://github.com/rndme/download
Download link on this site: https://static.tutorialpro.org/download/download-master.zip
CDN library: https://cdn.staticfile.org/downloadjs/1.4.8/download.min.js
NPM installation:
npm install downloadjs
The download.js library provides the download() function for downloading files.
The content to be downloaded can be a URL, string, Blob, or typed data array, or a dataURL representing file data as base64 or url-encoded string.
Regardless of the input format, download() saves the file with the specified filename and mime information in the same way as a server using the Content-Disposition HTTP header.
download(data, strFileName, strMimeType);
data - The data content to be downloaded, 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 be downloaded.
Examples
Text
Store the string into dlText.txt file and download:
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
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");
Asynchronous 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();
** Click to Share Notes
-
-
-