文件下载

Sep 24, 2023· 1 min read

常见文件下载方式

方式 1 利用a标签下载文件

JSX
export function Demo() { const imgUrl = 'https://w.wallhaven.cc/full/3l/wallhaven-3l2ldd.png'; return ( <div> <a href={imgUrl} download > 下载文件 </a> </div> ); }

方式 2 使用 BlobURL.createObjectURL

JS
async function downloadFile(url) { const response = await fetch(url); const data = await response.blob(); const downloadUrl = URL.createObjectURL(data); const a = document.createElement('a'); a.href = downloadUrl; a.download = 'file_name'; a.click(); URL.revokeObjectURL(downloadUrl); } downloadFile('https://w.wallhaven.cc/full/3l/wallhaven-3l2ldd.png');

方式 3 使用FormDataXMLHttpRequest

JS
function downloadFile(url) { const xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = 'blob'; xhr.onload = function () { if (this.status === 200) { const downloadUrl = URL.createObjectURL(this.response); const a = document.createElement('a'); a.href = downloadUrl; a.download = 'file_name'; a.click(); URL.revokeObjectURL(downloadUrl); } }; xhr.send(); } downloadFile('https://w.wallhaven.cc/full/3l/wallhaven-3l2ldd.png');