Bindings for dealing with file data from within KnockoutJS.


Clearly, you'll need KnockoutJS. You'll also want to include knockout-file.js.

In your HTML:

<input type="file" data-bind="file: file">

Example ViewModel:

var viewModel = {
  file: ko.observable()

Then, elsewhere in your code, you can do:

var textContent = viewModel.file.text();

If the user has selected a file, you will get the textual content of that file. You can get the filename (which is probably faked, for security reasons), using viewModel.file().

You may also access the data as: binaryString(), arrayBuffer(), dataURL().


This uses the FileReader() API, which means it is limited to modern browsers, and maybe not IE.

Because the FileReader API is asynchronous, it works best if you do things like have ko.computed() things that access this, as they will then automatically get updated when the file is selected/changed.

Currently, every data type is added when the file is selected. This is certainly a bad thing, as it means lots more memory is used than is likely necessary (unless you actually need the file data in all four forms). In the future, it should be possible to define what format you want the data in (and perhaps the data would then be accessed via file() instead of file.<dataType>()).

You can also replace the content: file.text('foo'). This should not be possible.