原生js下载文件
# js方法(适用于后台返回类型为url链接)
function getDownloadMb(e) {
const x = new window.XMLHttpRequest();
x.open('GET', e.currentTarget.dataset.fileUrl, true);
x.responseType = 'blob';
const fileName = e.currentTarget.dataset.fileName
const fileUrl = e.currentTarget.dataset.fileUrl
x.onload = () => {
const url = window.URL.createObjectURL(x.response);
const a = document.createElement('a');
a.href = url;
if (!fileName || fileName == 'null') {
a.download = fileUrl
} else {
a.download = fileName;
}
a.click();
};
x.send();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
上次更新: 2024/11/30, 11:44:47