Skip to content Skip to sidebar Skip to footer

Input File Selection Event Not Firing When Selecting The Same File In KnockoutJS And HTML

Probably this has a easy solution for JQuery but i am struggling to do with KnckoutJS. When i select the same file then event is not firing. I have a html like this

Solution 1:

Here is file uploading sample in knockout:

<input type="file" data-bind="event: {change: onFileChange}" id="fileUploadId">

<input type="button" data-bind="event: {click: resetFileInput}" value="Reset">

below is knockout js:

fileInput: any;

onFileChange(data, e) {
   this.uploadFile(data, e)
}

uploadFile(data, e) {

        var url = "/someUrl";
        this.fileInput = e.target;

        // getting file here
        var file = e.target.files[0];
       // preparing form data to post by uploading
        var formData = new FormData();
        formData.append("thefile", file);

        var xhr = new XMLHttpRequest();

       // posting the data to url
        xhr.open("POST", url, true);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4) {
                // ...
            } else {
               // ...
            }

        }
        xhr.send(formData);
        return true;
    }
     // something like this
     resetFileInput() {
            if (this.fileInput) {
                $(this.fileInput).val("");
            }
       }

Solution 2:

Found an workaround, not good solution though.

<i style="cursor:pointer;" title="{{$parent.texts().delete}}" class="fa fa-trash fa-fw" data-bind="click: function(){ $root.removeAttachment(this); }"></i>

added a remove button and reset the file content there.

function removeAttachment(file) {
            document.getElementById("documentattachment").value = "";   //resetting the file input             
            vm.attachments.removeAll();
            vm.fileDatas.removeAll();
        }

Post a Comment for "Input File Selection Event Not Firing When Selecting The Same File In KnockoutJS And HTML"