Download file using js knockout

Uploading files does not work with js knockout. I tried with the code below but did not work. Please indicate where I am mistaken.

This is my file control and button. I can not send the selected file from the client side to the server. Please suggest the best approach for this.

<input id="files" name="files" type="file" class="input-file" data-bind="file: FileProperties.FileName"/> <button data-bind="click : Upload">Upload</button> <script type="text/javascript"> ko.bindingHandlers.file = { init: function (element, valueAccessor) { alert('init'); $(element).change(function () { var file = this.files[0]; if (ko.isObservable(valueAccessor())) { valueAccessor()(file); } }); } </script> 
+7
javascript c #
source share
3 answers

I came up with this solution for my current project.

 <img class="myImage" data-bind="attr: {src: $root.photoUrl() || 'images/tempImage.png'}"/> <input data-bind="event: {change: $root.fileUpload}" type="file" accept="image/*" class="fileChooser"/> <script> var myController = function() { var self = this; this.photoUrl = ko.observable(); this.fileUpload = function(data, e) { var file = e.target.files[0]; var reader = new FileReader(); reader.onloadend = function (onloadend_e) { var result = reader.result; // Here is your base 64 encoded file. Do with it what you want. self.photoUrl(result); }; if(file) { reader.readAsDataURL(file); } }; }; </script> 
+16
source share

It looks like you need a special knockout binding to download files. There are various api / libs that handle all cases of errors with additional functions. Try this: https://github.com/TooManyBees/knockoutjs-file-binding

+4
source share
 <input type="file" id="FileName" style="width:180px" data-bind="value:addModel.InputFileName" /> function () { var files = $("#FileName").get(0).files; var data = new FormData(); for (var x = 0; x < files.length; x++) { data.append("file" + x, files[x]); } $.ajax({ type: "POST", url: '/api/Controller' + '/?id=' + id ), contentType: false, processData: false, data: data, success: function (result) {} error: function (xhr, status, p3, p4) {} }); } 
+1
source share

All Articles