Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery ajax, send form with input type file and Json

Tags:

jquery

file

ajax

I have a form with several inputs and other field.

I have a save button, and when I click, I send the form with ajax with jQuery :

$.ajax({
        type:       "POST",
        dataType:   "json",
        url:        $('#ajaxUrl').val(),
        data:       "action=save&" + form.serialize()
});

So, when I have only simple input like text, select etc.. it's ok. But if I have an input type file, I can't retrieve my file. $_FILES is always empty.

How can I do that as simply as possible ?

Edit : I don't want to use a plugin :)

like image 511
Clément Andraud Avatar asked Jul 18 '13 08:07

Clément Andraud


1 Answers

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 ;)

like image 115
HuckFin.7b Avatar answered Nov 12 '22 03:11

HuckFin.7b