众所周知,a标签中download属性可以更改下载文件的文件名。
但是只适用于同源文件,如果是跨域的话,download属性就会失效。
第一种方式:使用XMLHttpRequesthandleDownload(item) { var xml = new XMLHttpRequest(); xml.open('GET', item.fileUrl, true); xml.responseType = 'blob'; xml.onload = function () { var url = window.URL.createObjectURL(xml.response); var a = document.createElement('a'); a.href = url; a.download = item.fileName; a.click(); }; xml.send(); },
第二种方式:使用axios
import axios from 'axios' downloadFile(item) { axios .get(item.fileUrl, { responseType: 'blob' }) .then(res => { const blob = new Blob([res.data]) const link = document.createElement('a') link.href = URL.createObjectURL(blob) link.download =item.fileName link.click() URL.revokeObjectURL(link.href) }) .catch(console.error) },