-
Notifications
You must be signed in to change notification settings - Fork 60
/
file.ts
58 lines (54 loc) · 1.65 KB
/
file.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
/**
* Save and download file with the given data.
* @param data String data to save in the file.
* @param fileName Name of the downloaded file.
* @param contentType Content type of the file.
*/
export const saveFile = (
data: string,
fileName: string,
contentType: string = 'application/json',
) => {
const blob = new Blob([data], { type: contentType });
const tempAnchor = document.createElement('a');
tempAnchor.style.display = 'none';
tempAnchor.href = URL.createObjectURL(blob);
tempAnchor.download = fileName;
tempAnchor.click();
tempAnchor.remove();
};
/**
* Load a file from user by mocking an input element.
* @param onFileRead Callback when the file is read.
* @param contentType Content type of the file. Default 'application/json'.
*/
export const loadFile = (
onFileRead: (data: string) => void,
contentType: string = 'application/json',
) => {
// Create a mock input file element and use that to read the file
const inputFile = document.createElement('input');
document.body.appendChild(inputFile);
inputFile.type = 'file';
inputFile.accept = contentType;
inputFile.onclick = (e: any) => {
e.target.value = '';
};
inputFile.addEventListener('invalid', (e) => {
console.log(JSON.stringify(e));
});
const fileSelected = (e: any) => {
const configFile = e.target?.files[0];
const reader = new FileReader();
reader.onload = (e) => {
if (e.target && e.target.result) {
onFileRead?.(e.target.result.toString());
}
inputFile.remove();
};
reader.readAsText(configFile);
};
inputFile.oninput = fileSelected;
// inputFile.onchange = fileSelected;
inputFile.click();
};