This article mainly introduces the implementation of JavaScript file download and renaming code examples, in this article through the example code introduction is very detailed, for everyone’s learning or work has a certain reference learning value, need friends can refer to

By modifying theaIn the labeldownloadattribute

let downloadLink = document.createElement('a'); DownloadLink. Download = 'rename. Suffix '; Downloadlink. href = new URL(' download path, link '); downloadLink.click();Copy the code

This same source access is no problem, but a cross-domain is not good, try other methods, either report cross-domain error, or open the file in the current page, experience is quite bad.

The response data obtained with the request file address is converted toBlobThe file object

// @param {String} url Url of the target file // @param {String} filename Name of the file to save function download (URL, filename) { getBlob(url, function(blob) { saveAs(blob, filename); }) } function getBlob(url,cb) { let xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'blob'; xhr.onload = function() { if (xhr.status === 200) { cb(xhr.response); } } xhr.send(); } @param {Blob} Blob // @param {String} filename Specifies the name of the file you want to save. filename) { if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(blob, filename); } else { let link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = filename; link.click(); window.URL.revokeObjectURL(link.href); }}Copy the code

You can then rename the downloaded file by calling the courseDownload method

  courseDownload(url, filename);
Copy the code