通过后端返回的文件的服务器地址,实现文件的点击下载,而不是直接打开文件(浏览器支持预览的文件,访问地址时会直接打开,不支持预览的文件才会下载),以下方法就会直接打开,而不会在浏览器打开预览
import axios from "axios";
downLoad(data) {
axios({
url: data.url, // 文件路径
method: "GET",
responseType: "blob", // 设置响应类型为二进制流
})
.then((response) => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement("a");
// 提取文件地址中的文件后缀名,将其拼接在文件名后面,如果文件名包含后缀则不需要这一步
const arr = data.url.split(".");
const suffix = arr.length > 1 ? arr[arr.length - 1] : "";
link.href = url;
link.setAttribute("download", `${data.fileName}.${suffix}`); // 设置下载文件的名称
document.body.appendChild(link);
link.click();
})
.catch((error) => {
console.error("文件下载失败", error);
});
},