3

I have this following snippet for uploading files via Ajax post (using Knockout js library)

ko.bindingHandlers.fileUpload = {
init: function (element, valueAccessor) {
    $(element).after('<div class="progress"><div class="bar"></div><div class="percent">0%</div></div><div class="progressError"></div>');
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {

    var options = ko.utils.unwrapObservable(valueAccessor()),
        property = ko.utils.unwrapObservable(options.property),
        url = ko.utils.unwrapObservable(options.url);

    if (property && url) {

        $(element).change(function () {
            if (element.files.length) {
                var $this = $(this),
                    fileName = $this.val();
                alert(fileName);
                // this uses jquery.form.js plugin
                $(element.form).ajaxSubmit({
                    url: url, //WEB API URL
                    type: "POST",
                    dataType: "text", //I want to upload .doc / excell files
                    headers: { "Content-Disposition": "attachment; filename=" + fileName },
                    beforeSubmit: function () {
                        $(".progress").show();
                        $(".progressError").hide();
                        $(".bar").width("0%")
                        $(".percent").html("0%");
                    },
                    uploadProgress: function (event, position, total, percentComplete) {
                        var percentVal = percentComplete + "%";
                        $(".bar").width(percentVal)
                        $(".percent").html(percentVal);
                    },
                    success: function (data) {
                        $(".progress").hide();
                        $(".progressError").hide();
                        // set viewModel property to filename
                        bindingContext.$data[property](data);
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        $(".progress").hide();
                        $("div.progressError").html(jqXHR.responseText);
                    }
                });
            }
        });
    }
}

}

now my problem is creating the WEB API for this.

$(element.form).ajaxSubmit({
    url: url, //WEB API URL
    type: "POST",
    dataType: "text", //I want to upload .doc / excell files
    headers: { "Content-Disposition": "attachment; filename=" + fileName },

I want to upload Word/Excell document. Can someone give me an idea how to get this done in ASP.NET WEB API?

UPDATE:

I finally made an WEB API for this

  public class UploadController : ApiController
{

    public async Task<HttpResponseMessage> PostFormData()
    {
        // Check if the request contains multipart/form-data.
        if (!Request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
        }

        string root = HttpContext.Current.Server.MapPath("~/App_Data");
        var provider = new MultipartFormDataStreamProvider(root);
        try
        {
            // Read the form data.
            await Request.Content.ReadAsMultipartAsync(provider);

            // This illustrates how to get the file names.
            foreach (MultipartFileData file in provider.FileData)
            {
                Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                Trace.WriteLine("Server file path: " + file.LocalFileName);
            }
            return Request.CreateResponse(HttpStatusCode.OK);

            //return new HttpResponseMessage()
            //{
            //    Content = new StringContent("File uploaded.")
            //};

        }
        catch (System.Exception e)
        {
            return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
        }
    }

It works ok (data successfully uploaded) but the problem is, it seems like in doesnt hit this section after the data is succesfully uploaded.

  success: function (data) {
                        $(".progress").hide();
                        $(".progressError").hide();
                        // set viewModel property to filename
                        bindingContext.$data[property](data);
                    },

I have to inform the client of what the status of the upload.

lincx
  • 253
  • 2
  • 7
  • 15
  • 1
    It seems like you need some help on the server side with how to handle the form post. This answer may help provide some more insight in to that: http://stackoverflow.com/questions/10320232/how-to-accept-a-file-post-asp-net-mvc-4-webapi/10327789#10327789 – Kevin Nacios Jun 27 '13 at 01:34
  • if you're using firebug, try `console.log(data)` right after the success function – I.G. Pascual Mar 18 '14 at 10:47
  • You should probably also cite your source! http://www.asp.net/web-api/overview/advanced/sending-html-form-data,-part-2 – freedomn-m May 01 '15 at 09:20

0 Answers0