<a>
标签有个download属性可以自定义下载文件的文件名
1 2 3 4 5 6 7
| const url = '下载的文件url' const link = document.createElement('a') link.style.display = 'none' link.href = url link.setAttribute('download', '自定义名称') document.body.appendChild(link) link.click()
|
但是该属性仅支持同源路径自定义名称,当页面在a.baidu.com
下,文件在b.baidu.com
下时,定义该属性就失效了。
这时可以先下载文件,把文件转为blob(同源之后)再触发本地下载
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import axios from "axios";
export async function downloadFile(fileUrl, fileName) { if (!fileUrl) return; let res = await axios({ method: "get", url: fileUrl, responseType: "blob" }); let newUrl = window.URL.createObjectURL(res.data); let a = document.createElement("a"); a.href = newUrl; a.download = fileName; a.click(); a.remove(); window.URL.revokeObjectURL(newUrl); }
|
参考