0%

使用js下载文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var url = 'download/?filename=aaa.txt';
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = "blob";
xhr.onload = function () {
if (this.status === 200) {
var blob = this.response;
var reader = new FileReader();
reader.readAsDataURL(blob);
reader.onload = function (e) {
var a = document.createElement('a');
a.download = 'name';
a.href = e.target.result;
$("body").append(a);
a.click();
$(a).remove();
}
}
};
xhr.send()