参考: # 前端文件下载的正确打开方式
window.open(url)会触发浏览器默认行为,如果单纯只是直接创建一个a标签再触发点击事件,也是会触发浏览器的默认行为。
浏览器的默认行为:能预览就预览,预览不了再直接下载。
如果我不希望预览,该怎么做?
答:使用fetch,转换成blob,最后使用a标签下载
const fileName = ''
fetch(url)
.then((response) => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.blob();
})
.then((blob) => {
const url = window.URL.createObjectURL(new Blob([blob]));
const link = document.createElement("a");
link.href = url;
link.setAttribute("download", filename || "文件下载");// 一定要有这行,不然不会直接下载的
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
})
.catch((error) => {
console.error("上传异常:", error);
});