jQuery ajax, send form with input type file and Json jQuery ajax, send form with input type file and Json ajax ajax

jQuery ajax, send form with input type file and Json


Implementation for ASP.NET MVC:

To start making your form-wrapper :

<form id="inputform">    <input class="hide" type="file" name="file" id="file" /></form>

Сreate a client-handler to send:

$("#yourButton").bind('click', function () {    var data = new window.FormData($('#inputform')[0]);    $.ajax({        xhr: function () {              return $.ajaxSettings.xhr();        },        type: "POST",        data: data,        cache: false,        contentType: false,        processData: false,        url: "@Url.Action("MethodName", "ControllerName")",        success: function () { },        error: function () { },    });});

Do handler on the server side (controller):

    public ActionResult MethodName(HttpPostedFileWrapper file) {    var img = Image.FromStream(file.InputStream);       ....       return ..;    }

I hope this will help you save time ;)


form.serialize does not manage file inputs. You'll have to an XMLHttpRequest with formData as adeneo suggests, see example usage here. For older browsers, there are solutions using iframe and POSTing the form with the iframe as target. Some jquery plugins will do all that for you, like, say, JQuery-File-Upload (but plenty of others exist).


I found this little "vanilla" framework by querying "Using FormData Objects" on google.

used by:

AJAXSubmit(myForm);

just modify on

function ajaxSuccess (){/*here*/}

if you console.log() the response on ajaxSuccess you could see the data submitted to server. It is on submittedData property.