介绍了三种常见文件下载方式:1) 使用<a>标签直接下载;2) 通过Blob和URL.createObjectURL实现动态下载;3) 利用FormData与XMLHttpRequest异步获取并触发下载。均支持设置自定义文件名。
常见文件下载方式
a标签下载文件export function Demo() {
const imgUrl = 'https://w.wallhaven.cc/full/3l/wallhaven-3l2ldd.png';
return (
<div>
<a
href={imgUrl}
download
>
下载文件
</a>
</div>
);
}
Blob 和 URL.createObjectURLasync 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');
FormData 和 XMLHttpRequestfunction 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');