Upgrade your file inputs to automatically read their selected file(s) in the background. Just include the autoload.js file in your project and you are good to go.
The autoload.js will once the DOM is ready find all input[type=file]
and
attach the needed infrastructure for it to automatically read the file(s) that
the user has chosen. This can be either from the input[type=file]
or dragged
and dropped onto one of its labels.
Every time this happens it creates a new FileReader
for each File
chosen and
starts the reading. Access to this FileReader
is provided through a new
property reader
on the corresponding File
.
If you insert any input[type=file]
dynamically and want to enable automatic
reading, make sure to call FileReader.auto
on those elements. It is safe to
call it multiple times on the same element. It remembers if it already has been
enabled.
In order to avoid polluting the global namespace autoload.js adds its
public API to the native FileReader
class as static methods.
This specifies the default format for automatic file reading. This is the part
after readAs
on all FileReader
instances. The default value is DataURL
,
see MDN for the full list.
This enables automatic file reading for the provided element in the provided
format. The latter defaults to FileReader.format
, see above.
All events from the native FileReader
are broadcasted onto the
input[type=file]
element that autoload.js is attached to. These all have
the event.relatedTarget
set to the File
object corresponding to the
FileReader
that originated the event.
This is useful when you have the multiple attribute set, since you then will
receive events from more then one FileReader
object.
To make it easier to handle multiple files, and to support drag'n'drop, it
fires a few extra events. These are CustomEvent
and have their detail
property set to the FileList
for the files chosen by the user.
This event is triggered after the automatic reading completed successfully for all files.
This event is triggered as the automatic reading is started.
This event is triggered after the automatic reading is completed for all files. This is independent if the reading was successful or failed.
This also includes a small AngularJS directive that listens on the above events and properly integrates with ngModel so you can just use it as any other input field. Include the directive.js and inject "angular-file-input" into your application.
For the vanilla JavaScript version, it requires the File API and a fairly modern browser. Make sure you test it on all platforms you need to support.
Because of the way drag'n'drop works, you can't rely on the files
property on
the input[type]
element for the list of files the user has chosen. Instead
listen for one of the above custom events which unifies this for you.
This code is licensed under MIT, see the LICENSE.md file for details.