-
Notifications
You must be signed in to change notification settings - Fork 0
/
gs-utils-files.js
77 lines (64 loc) · 1.63 KB
/
gs-utils-files.js
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
"use strict";
function GSUloadJSFile( src ) {
return new Promise( resolve => {
const js = GSUcreateElement( "script", { src, type: "text/javascript" } );
js.onload = resolve;
document.head.append( js );
} );
}
function GSUgetFileContent( file, format ) {
return new Promise( res => {
const rd = new FileReader();
rd.onload = e => res( e.target.result );
switch ( format ) {
case "text": rd.readAsText( file ); break;
case "array": rd.readAsArrayBuffer( file ); break;
}
} );
}
function GSUdownloadURL( name, url ) {
const a = GSUcreateA( {
href: url,
download: name,
target: "_blank"
} );
document.body.append( a );
a.click();
a.remove();
}
function GSUdownloadBlob( name, blob ) {
GSUdownloadURL( name, URL.createObjectURL( blob ) );
}
function GSUgetFilesDataTransfert( dataTransferItems ) {
const files = [];
return new Promise( res => {
const proms = [];
for ( const it of dataTransferItems ) {
const ent = it.webkitGetAsEntry();
if ( ent ) {
proms.push( _GSUgetFilesDataTransfertRec( files, ent ) );
}
}
Promise.all( proms ).then( () => res( files ) );
} );
}
function _GSUgetFilesDataTransfertRec( files, item, path = "" ) {
return new Promise( res => {
if ( item.isFile ) {
item.file( f => {
f.filepath = path + f.name;
files.push( f );
res( f );
} );
} else if ( item.isDirectory ) {
const dirReader = item.createReader();
dirReader.readEntries( entries => {
const proms = [];
for ( let ent of entries ) {
proms.push( _GSUgetFilesDataTransfertRec( files, ent, path + item.name + "/" ) );
}
res( Promise.all( proms ) );
} );
}
} );
}