1.利用HTML 5 里面为标签添加了一个download的属性
<a href="http://somehost/somefile.zip" download="filename.zip">Download file</a>
JavaScript实现原理
var a = document.createElement("a");
var url = window.URL.createObjectURL(blob);
var filename = "what-you-want.txt";
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
2.window.open()方式
<button type="button" id="btn1">下载一个zip(方法1)</button>
<button type="button" id="btn2">下载一个zip(方法2)</button>
$eleBtn1.click(function() {
window.open(
"https://codeload.github.com/douban/douban-client/legacy.zip/master"
);
});
- 缺点:浏览器会打开一个新窗口,然后迅速自动关闭,体验非常不好。
3.通过form提交
$eleBtn2.click(function() {
var $eleForm = $("<form method='get'></form>");
$eleForm.attr(
"action",
"https://codeload.github.com/douban/douban-client/legacy.zip/master"
);
$(document.body).append($eleForm);
//提交表单,实现下载
$eleForm.submit();
});
4.需要上传token的方式(项目中遇到)
function createObjectURL(object) {
return window.URL ? window.URL.createObjectURL(object) : window.webkitURL.createObjectURL(object);
}
var xhr = new XMLHttpRequest();
var formData = new FormData();
xhr.open("get", "url"); //url填写后台的接口地址,如果是post,在formData append参数(参考原文地址)
xhr.setRequestHeader("access-token", sessionStorage.getItem("access-token")); // 设置请求头,携带token
xhr.responseType = "blob";
xhr.onload = function(e) {
if (this.status == 200) {
var blob = this.response;
var filename = "设备导出.xls"; // 文件名称
console.log(this.response);
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, filename);
} else {
var a = document.createElement("a");
var url = createObjectURL(blob);
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
}
}
};
xhr.send(formData);
- 后台需要token验证,上面几种无法实现要求,这种方法可以达到要求。
参考:
https://segmentfault.com/a/1190000005863250
https://www.jianshu.com/p/3d834f126c59
网友评论