需求: 不调用接口,根据单个url下载网络内容 实现方法:自定义执行浏览器默认下载行为
const downloadFile = (url: string, fileName: string) => {
// 使用 fetch 获取文件内容
fetch(url)
.then((response) => response.blob())
.then((blob) => {
// 创建一个隐藏的 <a> 标签并触发下载
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = fileName;
link.style.display = 'none';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href); // 释放 URL 对象
})
.catch((error) => console.error('Download failed:', error));
};