Vue|vue实现文件下载功能

方法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的形式走的是调接口的形式,就比较好了,有问题的话,可以很方便的定位问题,指定文件链接出问题了,页面也不会跳转到空白页面。

    推荐阅读