方法1使用 超链接 href来实现
方法2 掉接口走 blob形式
里面有一个小坑,记得配置下axios,
responseType: "blob"
要不然下载的文件会偏大
async certDownload() {
const res = await axios.get(this.downloadUrl, { responseType: "blob" });
const content = res.data;
const blob = new Blob([content], { type: "blob" });
let fileName;
for (const item of res.headers["content-disposition"].split(";
")) {
if (item.indexOf("filename") !== -1) {
fileName = item.split("=")[1];
}
}
// 非IE下载
const elink = document.createElement("a");
elink.download = fileName;
elink.style.display = "none";
elink.href = https://www.it610.com/article/URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
URL.revokeObjectURL(elink.href);
// 释放URL 对象
document.body.removeChild(elink);
},
两种方法比较:
使用超链接的方式,实际上走的是href的形式,浏览器跳转到指向的URL,发现是一个文件的话,就去下载,如果URL出现了问题,浏览器就会跳到这个URL页面,前端页面显示空白,生产环境可能存在问题,如果指定的文件链接报错500或者404 之类的非200,300的错误,就会跳转到一个空白页面,很尴尬!
【Vue|vue实现文件下载功能】使用blob的形式走的是调接口的形式,就比较好了,有问题的话,可以很方便的定位问题,指定文件链接出问题了,页面也不会跳转到空白页面。
推荐阅读
- JavaScript|vue 基于axios封装request接口请求——request.js文件
- 前端|web前端dya07--ES6高级语法的转化&render&vue与webpack&export
- 前端开发|Vue2.x API 学习
- vue|Vue面试常用详细总结
- vue|电商后台管理系统(vue+python|node.js)
- 腾讯TEG实习|腾讯实习——Vue解决跨域请求
- Vue|vue-router 详解
- vue|vue3替代vuex的框架piniajs实例教程
- Vue|Vue3.0的插槽是如何实现的()
- 前端|面试官(谈谈Vue和React的区别())