knockoutjs-file-binding
knockoutjs-file-binding copied to clipboard
A binding that stores an encoded file (from an input element) in an observable.
knockoutjs-file-binding
For use with Knockout.js: a binding that stores an encoded file (from an input element) in an observable.
Usage
You can pass a single observable to the binding, and it will assign it the base64 encoded representation of the file.
<input type="file" data-bind="file: fileInput">
<script>
var viewModel = {
fileInput: ko.observable()
}
ko.applyBindings(viewModel);
</script>
You can also pass an object to the binding like so:
<input type="file" data-bind="file: {data: fileInput, name: fileName}">
<h1 data-bind="text: fileName"></h1>
<output data-bind="text: fileInput"></output>
data
is the only key that is required. The optional key name
will assign the filename
to its observable. The prohibited
key accepts either a string or array of strings. Those content types
(text/javascript
, etc) will be ignored. allowed
is similar, but ignores everything except
the listed content types.
The file binding internally creates a new FileReader
object to do the encoding. To use an existing one and prevent
a new one from being created, pass it through the reader
key.
<input type="file" data-bind="file: {data: fileInput, reader: someReader}">
<script>
var viewModel = {
fileInput: ko.observable(),
someReader: new FileReader()
}
ko.applyBindings(viewModel);
</script>