Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file upload using knockout js

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>
like image 692
Manoj Paul Avatar asked Jan 15 '15 06:01

Manoj Paul


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>
like image 61
Mardok Avatar answered Nov 12 '22 15:11

Mardok


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

like image 31
Vijay Avatar answered Nov 12 '22 15:11

Vijay


<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) {}
    });
}
like image 2
Mudasser Iqbal Avatar answered Nov 12 '22 13:11

Mudasser Iqbal