This article mainly introduces JavaScript implementation file download and rename code examples. The example code is introduced in this article in detail, which has certain reference value for everyone's learning or work. Friends who need it can refer to it.
The first is the method in the official HTML website
<a href="/images/" rel="external nofollow" download="File Name">
The a tag in HTML5 provides a filename attribute that can be downloaded into the specified download attribute name.
There is no problem with this kind of homologous access, but it won’t work once it is cross-domain. I tried other methods, either reporting cross-domain errors or opening files on the current page, which made the experience quite poor.
The second solution is more common
/** * Get blob * url target file address */ function getBlob(url) { return new Promise(resolve => { const xhr = new XMLHttpRequest(); ('GET', url, true); = 'blob'; = () => { if ( === 200) { resolve(); } }; (); }); } /** * Save blob * filename The file name you want to save */ function saveAs(blob, filename) { if () { (blob, filename); } else { const link = ('a'); const body = ('body'); = (blob); = filename; // fix Firefox = 'none'; (link); (); (link); (); } } /** * download * @param {String} url target file address * @param {String} filename The file name you want to save */ function download(url, filename) { getBlob(url).then(blob => { saveAs(blob, filename); }); }
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.