-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
77 lines (61 loc) · 1.49 KB
/
index.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
/**
* Module Dependencies
*/
var event = require('event');
/**
* Expose `FilePicker`
*/
module.exports = FilePicker;
/**
* Input template
*/
var form = document.createElement('form');
form.style.margin = '0px';
form.innerHTML = '<input type="file" style="top: -1000px; position: absolute" aria-hidden="true">';
document.body.appendChild(form);
var input = form.childNodes[0];
/**
* Already bound
*/
var bound = false;
/**
* Opens a file picker dialog.
*
* @param {Object} options (optional)
* @param {Function} fn callback function
* @api public
*/
function FilePicker(opts, fn){
if ('function' == typeof opts) {
fn = opts;
opts = {};
}
opts = opts || {};
// multiple files support
input.multiple = !!opts.multiple;
// directory support
input.webkitdirectory = input.mozdirectory = input.directory = !!opts.directory;
// accepted file types support
if (null == opts.accept) {
delete input.accept;
} else if (opts.accept.join) {
// got an array
input.accept = opts.accept.join(',');
} else if (opts.accept) {
// got a regular string
input.accept = opts.accept;
}
// listen to change event (unbind old one if already listening)
if (bound) event.unbind(input, 'change', bound);
event.bind(input, 'change', onchange);
bound = onchange;
function onchange(e) {
fn(input.files, e, input);
event.unbind(input, 'change', onchange);
bound = false;
}
// reset the form
form.reset();
// trigger input dialog
input.click();
}