File upload not working using knockout js. I have tried with below code but not working. Please mention where I am doing wrong.
This is my file control and button. I am unable to send the selected file from the client side to the server. Please suggest what is 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>
                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>
                        Seems like you need a custom knockout binding for file uploading. There are various api/libs available that handles all the error cases with additional features. Try this: https://github.com/TooManyBees/knockoutjs-file-binding
<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) {}
    });
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With