vue根据文件地址下载文件。vue下载文件的时候给header传递token 电脑版发表于:2020/1/16 10:19 **最简单的方式一句话搞定** ``` window.location.href = res.success.url ``` **动态创建a标签触发点击事件** ``` //根据文件地址下载文件 downLoadByUrL(fileUrlInp,fileNameInp){ let url = fileUrlInp const a = document.createElement('a') a.href = url //下载的文件地址 a.download = fileNameInp // 下载后文件名 a.style.display = 'none' document.body.appendChild(a) a.click() // 点击下载 document.body.removeChild(a) // 下载完成移除元素 } ``` 使用 ``` //下载实验资料 downLoadResource() { const _this = this //通过实验id获取实验素材的url地址 _this.$http.get('/oss/api/SmartFiles/GetFileUrl', { fileId: _this.fileId, downloadName: "素材" }).then(res => { if(res.code==0) { //根据返回的实验素材url地址去下载 _this.downLoadByUrL(res.data.url,"素材") } }) }, ``` **如果使用a标签下载跨域,可以使用下面的方法** ``` const fileurl = fileUrlInp.replace(/(http|https):/, '') window.open(fileurl) ``` **当然还有其他方法比如:** ``` const downloadRes = async () => { let response = await fetch(url); let blob = await response.blob(); let objectUrl = window.URL.createObjectURL(blob); let a = document.createElement('a'); a.href = objectUrl; a.download = res.success.fileName; a.click() a.remove(); } downloadRes(); ``` **vue下载文件的时候给header传递token** 参考:https://www.tnblog.net/aojiancc2/article/details/7969