devongovett/standards — Issue #1: JavaScript "Choose File" API
Author: devongovett
Created: 2012-02-15 10:30:13+00:00
State: open

Currently it's way more difficult to bring up a "Choose File" dialog from JavaScript than it should be. In most browsers, you can create a hidden element and trigger the click event on it, but this is clunky and has some issues. For example, in certain browsers the element cannot be set to display: none, or visibility: hidden, so usually we just absolutely position it way off the screen. Then you can try to reuse this input for multiple UI elements you create yourself, but make sure to clear the file selection after each change or two of your virtual file inputs sharing the control won't be able to pick the same file (no change event). And how do you clear it? There is no way, so you wrap it in a form element, and call `form.reset()`. Ugh.

This is way too hard. Why do we need that extra element sitting around? I propose a simple API for this below. It would be attached to the `MouseEvent` interface so that one could only call the API from within a `mousedown`, `mouseup`, or `click` event for security reasons (touch events too?), and it could support all the features that the native file inputs support. Here's an example:

```javascript
element.onclick = function(e) {
e.showFilePicker(function(files) {
// files would be a FileList just as normal
});
}
```

Or a more complex example with options:

```javascript
element.onmouseup = function(e) {
e.showFilePicker({
accept: 'image/*',
directories: true,
callback: function(files) {
// do something
}
});
}
```

I think it is very obvious what these options would do. The API would, of course, be asynchronous and callback based, and return a FileList just as the native file input element does already.

Anyway, just some thoughts. :)