Input file selection event not firing when selecti

2019-09-10 19:20发布

问题:

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

                    <label class="upload">
                        <input id="documentattachment" name="documentattachment" multiple type="file" data-bind="event: { change: function() { uploadSelected($element.files) } }" />
                        {{texts().attachmentFile}}
                    </label>

and in viewmodel i have code like this.

function uploadSelected(file) {

            if (!vm.uploadOnSubmit()) {
                if (!session.hasPermission(session.permissions.Documents, vm.clientNr())) {
                    toastr.error(vm.texts().permissionDenied);
                    return false;
                } else {
                    var att = new Attachment(
                        file[0].lastModifiedDate,
                        file[0].name,
                        0,
                        (vm.uploadOnSubmit() ? true : false));
                    vm.attachments.push(att);
                    vm.fileDatas.push(file[0]);
                    return true;
                }
            } 
        }

my question is that how can get file even i select the same file.
Thanks

回答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("");
            }
       }


回答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();
        }