JS文件下载

根据URL下载文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
</head>

<body>
<button onclick="downloadFile('https://example.com/sample.pdf')">下载文件</button>
<script>
function downloadFile(url) {
const a = document.createElement('a');
a.href = url;
a.target = '_blank';
a.download = url.split('/').pop();
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
</script>
</body>

</html>

JS

1
2
3
4
5
6
7
8
9
export function downloadFile(url) {
const a = document.createElement('a')
a.href = url
a.target = '_blank'
a.download = url.split('/').pop()
document.body.appendChild(a)
a.click()
document.body.removeChild(a)
}