《1》a 标签的 href 有很大的关系, href 属性的地址必须是 同源 URL,否则,download 就会不起作用。
1. 同源 URL 会进行 下载 操作
2. 非同源 URL 会进行 导航 操作
3. 非同源的资源 仍需要进行下载,那么可以将其转换为 blob: URL 形式
《2》a标签的 download 属性是HTML5新增的属性,它可以使 a 标签的 href 属性进行下载,download 属性为下载后的 文件名,可能会通过 JavaScript 进行动态修改 或者 Content-Disposition 中指定的 download 属性优先级高于 a.download
1、同源URL (静态)
<a href="http://127.0.0.1:3000/1.jpg" download="1.jpg">下载</a>
2. 同源URL (动态)
function aTagDownload(url, filename){
const a = document.createElement("a"); // 创建 a 标签
a.href = url; // 下载路径
a.download = filename; // 下载属性,文件名
a.style.display = "none"; // 不可见
document.body.appendChild(a); // 挂载
a.click(); // 触发点击事件
document.body.removeChild(a); // 移除
}
3. 非同源URL (Blob)
function download(path, fileName=''){
if (!fileName) fileName = '123.jpg'
fetch(path).then(res =>
res.blob()
).then((blob) => {
let objectUrl = URL.createObjectURL(blob); // 创建 url 对象
aTagDownload(objectUrl,fileName); // 调用 上面 [2] 动态方式
}).catch((err) => {
console.log('Request Failed', err)
})
}