1,最简单的方法是
window.open("url", "_blank");
大概原理为:window.open() 作用为打开一个网页,当浏览器检测到url不是一个网页时,他会帮助你进行下载或者打开该文件,不支持对request header的编辑
于此类似的还有
window.location.href = url;
均不建议使用
2,建议采用blob与Ajax相结合的方法,具体方法参见
http://www.it1352.com/885919.html 之解决方案
此时后端会将整个文件通过文件流的方式传给前端,前端接收后用blob进行文件的还原
代码如下:
function downloadFile(url, headers, filename) { function handleFile(data) { console.log(this.response || data); var file = URL.createObjectURL(this.response || data); filename = filename || url.split("/").pop(); var a = document.createElement("a"); // if `a` element has `download` property if ("download" in a) { a.href = file; a.download = filename; document.body.appendChild(a); a.click(); document.body.removeChild(a); } else { // use `window.open()` if `download` not defined at `a` element window.open(file) } } var request = new XMLHttpRequest(); request.responseType = "blob"; request.onload = handleFile; request.open("GET", url); for (var prop in headers) { request.setRequestHeader(prop, headers[prop]); } request.send(); } downloadFile("/path/to/resource/", {"x-content": "abc"}, "filename.zip")
3,通过form表单进行下载
参见:
https://blog.csdn.net/weixin_33812433/article/details/92508393
4,如果是excel等文件格式应该还可以通过将数据流在前端形成excel文件的方式进行下载,资料未搜集