Download
coderljw 2024-10-13 大约 1 分钟
# 1. 下载文件
/**
* @param {string} url 下载链接
* @param {string} name 保存文件名称
*/
export const downloadFile = (url: string, name: string) => {
const a = document.createElement('a')
a.href = url
a.download = name
document.body.appendChild(a)
a.click()
a.remove()
}
1
2
3
4
5
6
7
8
9
10
11
12
2
3
4
5
6
7
8
9
10
11
12
# 2. 下载二进制数据
/**
* @param {Blob} blob 下载二进制对象
* @param {string} name 保存文件名称
*/
export const downloadFile = (blob: Blob, name: string) => {
const a = document.createElement('a')
const url = window.URL.createObjectURL(blob)
a.href = url
a.download = name
document.body.appendChild(a)
a.click()
a.remove()
window.URL.revokeObjectURL(url)
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 3. 使用 FileSaver 下载
import { saveAs } from 'file-saver'
saveAs('Blob/File/Url', 'name')
1
2
3
2
3
# 4. 打成压缩包下载
import JSZip from 'jszip'
const zip = new JSZip()
files.forEach((i) => zip.file(i.name, i))
const content = await JSZip.generateAsync({ type: 'blob' })
saveAs(content, name)
1
2
3
4
5
6
2
3
4
5
6
# 5. download
import { saveAs } from 'file-saver'
import JSZip from 'jszip'
/**
* @name 下载文件
* @description 多文件将打成压缩包下载
*/
export const download = async (
data?: string | Blob | File | { blob: Blob; name: string }[] | File[],
name?: string,
) => {
if (!data) return
if (data instanceof File) {
return saveAs(data, name ?? data.name)
}
if (typeof data === 'string' || data instanceof Blob) {
return saveAs(data, name)
}
if (Array.isArray(data)) {
if (data.length === 1) {
const content = data[0]
if (content instanceof File) saveAs(content, content.name ?? name)
else saveAs(content.blob, content.name ?? name)
}
const zip = new JSZip()
data.forEach((i) => {
if (i instanceof File) zip.file(i.name, i)
else zip.file(i.name, i.blob)
})
const content = await JSZip.generateAsync({ type: 'blob' })
return saveAs(content, name)
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37