Avi
Avi

Reputation: 35

FileUpload using Knockout in MVC

I need to Upload all type of files using knockout js. I am using MVC 4.0 and i need to Save file separately in a folder. Once i have Uploaded File i need to show it in Grid(FileName, Date Created and Type of File).

This is my View and Included the Knockout scripts.

var ViewModel = function () {
    var self = this;
    self.fileInput = ko.observable();
    self.fileName = ko.observable();

    var Data = {
enter code here
        file: self.fileInput,
        FileName: self.fileName
    };
    self.save = function () {
        //Ajax call to Insert the Employee
        $.ajax({
            type: "POST",
            url: "/Home/FileUpload",
            data: ko.toJSON(Data),
            contentType: "application/json",
            dataType: 'json',
            //cache: false,
            mimeType: "multipart/form-data",
            //processData: false,
            success: function () {
                alert("successful");
            },
            error: function () {
                alert("fail");
            }
        });
    }

}
var vm = new ViewModel();
ko.applyBindings(vm);



    <html>
      <body>
        <div>
    <form method="post">
        <span>File</span>
        <input type="file" id="fileUpload" name="fileUpload" data-bind="file: {data: fileInput, name: fileName}" />

        <input type="button" id="btnUpload" data-bind="click: save" value="Upload" formenctype="multipart/form-data" />
    </form>
</div>
</body>
</html>

emphasized text

So kindly help me out since i am new to knockout.

Upvotes: 2

Views: 3844

Answers (1)

Kshitiz Jaiswal
Kshitiz Jaiswal

Reputation: 123

First you need to make a FormData object and then look for files and append it to FormData.

var data = new FormData();
var files = $("#yourfileID").get(0).files;

data.append("KeyName", files[0]);

Now to send data to your Controller make a ajax call.

var ajaxRequest = $.ajax({
    type: "POST",
    url: yourURL,
    contentType: false,
    processData: false,
    data: data ,
    success: function (data) {
        //your callback goes here
    }
});

Now Inside your controller you can do something like this

public HttpResponseMessage AcgDocumentUpload() {
    if (HttpContext.Current.Request.Files.AllKeys.Any()) {
        var httpPostedFile = HttpContext.Current.Request.Files["KeyName"];
    }
}

P.S. you can also make XMLHttpRequest() to send data

Upvotes: 2

Related Questions