Search code examples
jqueryasp.netwebasp.net-web-apijquery-file-upload

File upload using Web API


I am trying to implement file upload (excel files) using,

Visual Studio 2012,
ASP.NET Web Forms,
jquery,
Web API
Browser: IE 8

I tried to follow online examples but they were using FormData and it is not working for me.

$('#ImportFileBtn').on('click', function () {

        var fileName = $('#ImportFileSelection').val();

        var data = "<form method='post' enctype='multipart/form-data'><body><input type='file' id='facilityFile' value='"+fileName +"' /></body></form>"

        $.ajax({
            type: "POST",
            url: "api/Import/ProcessImport",
            contentType: false,
            processData: false,
            data: data,
            success: function (messages) {
                alert('ok');
            },
            error: function () {
                alert("Error while invoking the Web API");
            }
        });
    });

Please suggest me how to upload an excel file to Web API controller with the above tools and technology.

Thanks, Vim


Solution

  • The problem is that IE8/9 do not know about FormData. There are several jQuery plug-ins you can use to work around this problem. Here are some libraries you could use (not a complete list):

    This is not a perfect option, but a plugin will make some things easier. Some of them need a lot of extra code. If you just need this functionality, choose one that integrates into jQuery's ajax method (have done this in a project some time ago, but can't remember the name of the library I used).

    UPDATE

    Just for the records: The library I used is called jQuery iFrame-Transport, because I had to support very old versions of IE.