1. A. Simple setting of the href method
// Download the filefunction downloadFile() { const link = ('a'); = 'none'; // Set the download address ('href', ); // Set file name ('download', ); (link); (); (link); }
2. A. Tags use blob data type method
async function download(downloadUrl: string, downloadFileName: string ) { const blob = await getBlob(downloadUrl); saveAs(blob, downloadFileName ); } function getBlob(url: string) { return new Promise<Blob>((resolve, reject) => { const xhr = new XMLHttpRequest(); ('GET', url, true); = 'blob'; = () => { if ( === 200) { resolve(); } else { reject(new Error(`Request failed with status ${}`)); } }; = () => { reject(new Error('Request failed')); }; (); }); } function saveAs(blob: Blob, filename: string) { const link = ('a'); const body = ; = (blob); = filename; // hide the link = 'none'; (link); (); (link); (); }
Attachment: Cross-domain download and modify file names through blob
Call the following method when clicking
function load(file) { ().then(blob => { (blob, ); }); },
//Download the url through the file to get the corresponding blob object
getBlob(url) { return new Promise(resolve => { const xhr = new XMLHttpRequest(); ('GET', url, true); = 'blob'; = () => { if ( === 200) { resolve(); } }; (); }); },
//Download filesaveAs(blob, filename) { var link = ('a'); = (blob); = filename; (); }
Summarize
This is the end of this article about JS downloading files and renaming files through URLs. For more related JS URL downloading and renaming content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!