-
Notifications
You must be signed in to change notification settings - Fork 29
/
processors.ts
78 lines (59 loc) · 2.29 KB
/
processors.ts
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import type { ExportType } from './types.js'
export function generateDataURI (content: string, type: ExportType, byBlob: boolean): string {
switch (type) {
case 'txt': {
const blobType = 'text/plain;charset=utf-8'
if (byBlob) return URL.createObjectURL(new Blob([content], { type: blobType }))
return `data:,${blobType}` + encodeURIComponent(content)
}
case 'css': {
const blobType = 'text/css;charset=utf-8'
if (byBlob) return URL.createObjectURL(new Blob([content], { type: blobType }))
return `data:,${blobType}` + encodeURIComponent(content)
}
case 'html': {
const blobType = 'text/html;charset=utf-8'
if (byBlob) return URL.createObjectURL(new Blob([content], { type: blobType }))
return `data:,${blobType}` + encodeURIComponent(content)
}
case 'json': {
const blobType = 'text/json;charset=utf-8'
if (byBlob) return URL.createObjectURL(new Blob([content], { type: blobType }))
return `data:,${blobType}` + encodeURIComponent(content)
}
case 'csv': {
const blobType = 'text/csv;charset=utf-8'
if (byBlob) return URL.createObjectURL(new Blob([content], { type: blobType }))
return `data:,${blobType}` + encodeURIComponent(content)
}
case 'xls': {
const blobType = 'text/application/vnd.ms-excel;charset=utf-8'
if (byBlob) return URL.createObjectURL(new Blob([content], { type: blobType }))
return `data:,${blobType}` + encodeURIComponent(content)
}
case 'xml': {
const blobType = 'text/application/xml;charset=utf-8'
if (byBlob) return URL.createObjectURL(new Blob([content], { type: blobType }))
return `data:,${blobType}` + encodeURIComponent(content)
}
default : {
return ''
}
}
}
export function downloadFile (content: string, type: ExportType, fileName: string = 'download', byBlob = true): void {
const dataURI = generateDataURI(content, type, byBlob)
const anchor = document.createElement('a')
anchor.href = dataURI
anchor.download = fileName
anchor.setAttribute('style', 'visibility:hidden')
document.body.appendChild(anchor)
anchor.dispatchEvent(
new MouseEvent('click', {
bubbles: false,
cancelable: false,
view: window,
}),
)
document.body.removeChild(anchor)
}