jQuery ajax, send form with input type file and Json
ajax, file, jquery
Solution
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 ;)
Problem
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 :)