前言
前端开发过程中,总会遇到点击链接下载。这个时候可以借助 2 种方法解决。一种是用 a 标签的 download,第二种是按钮点击之后调用接口来下载。2 种方法最好确定文件没有跨域现象。
a 标签 download
1 2 3 4 5 6 7 8 9
| downloadFile(url, fileName) { let aLink = document.createElement("a"); document.body.appendChild(aLink); aLink.setAttribute("href", url); aLink.setAttribute("download", fileName); aLink.click(); document.body.removeChild(aLink); },
|
ajax 或者 fetch 访问下载
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
downloadFile(url, filename) { this.getBlob(url, function(blob) { this.saveAs(blob, filename); }); }, getBlob(url, cb) { let xhr = new XMLHttpRequest(); xhr.open("GET", url, true); xhr.responseType = "blob"; xhr.onload = function() { if (xhr.status === 200) { cb(xhr.response); } }; xhr.send(); }
saveAs(blob, filename) { if (window.navigator.msSaveOrOpenBlob) { navigator.msSaveBlob(blob, filename); } else { var link = document.createElement("a"); var body = document.querySelector("body"); link.href = window.URL.createObjectURL(blob); link.download = filename; link.style.display = "none"; body.appendChild(link); link.click(); body.removeChild(link); window.URL.revokeObjectURL(link.href); } }
|