JSFiddle - React, Tailwind, and code Playground
HTML
<input data-bind="file: files" type="file" multiple />
<div data-bind="foreach: fileUploads">
<p><label>Name</label><span data-bind="text: name"></span></p>
<p><label>Progress</label><span data-bind="text: progress"></span></p>
</div>
CSS
label {
display: block;
width: 100px;
float: left;
}
JavaScript
(function () {
ko.bindingHandlers.file = {
init: function (element, valueAccessor, allBindingsAccessor) {
ko.utils.registerEventHandler(element, "change", function () {
writeValueToProperty(valueAccessor(), allBindingsAccessor, "file", element.files);
});
},
update: function (element, valueAccessor) {
if (ko.utils.unwrapObservable(valueAccessor()) == null) {
element.value = "";
}
}
};
var writeValueToProperty = function (property, allBindingsAccessor, key, value, checkIfDifferent) {
if (!property || !ko.isObservable(property)) {
var propWriters = allBindingsAccessor()['_ko_property_writers'];
if (propWriters && propWriters[key])
propWriters[key](value);
} else if (ko.isWriteableObservable(property) && (!checkIfDifferent || property.peek() !== value)) {
property(value);
}
};
} ());
MasterViewModel = function() {
this.files = ko.observable();
this.fileUploads = ko.observableArray();
this.files.subscribe(this.onFilesAdded, this);
};
MasterViewModel.prototype = {
onFilesAdded: function(files) {
ko.utils.arrayForEach(files, function(file) {
this.fileUploads.push(new FileUploadViewModel(file));
}.bind(this));
}
}
FileUploadViewModel = function(file) {
this.bufferSize = 8192;
this.file = file;
this.reader = new FileReader();
this.total = this.file.size / this.bufferSize;
this.current = ko.observable(0);
this.progress = ko.computed(this.getProgress, this);
this.name = this.file.name;
this.reader.onload = this.onLoadPart.bind(this);
this.loadPart();
};
FileUploadViewModel.prototype = {
getProgress: function() {
return (this.current() / this.total * 100) + "%";
},
loadPart: function() {
var start = this.current() *...