It is possible to submit files using "multipart/form-data" and ajax. There are many sites out there that show complicated ways of doing this when it is really easy. It simply requires a little configuration of the jquery ajax process and grabbing your form data using the FormData() function.
Using the following method, you can submit multiple files and are not just limited to one.
Lets take a look at our form.
<form id="data">
<input type="hidden" name="id" value="123" readonly="readonly">
User Name: <input type="text" name="username" value=""><br />
Profile Image: <input name="profileImg[]" type="file" /><br />
Display Image: <input name="displayImg[]" type="file" /><br />
<input type="submit" value="Submit">
</form>
The above form has a hidden field, a user name field, and then two file image fields that we are going to submit to our PHP processing page.
Now lets look at the jQuery used to submit the form using "multipart/form-data" and ajax.
//Program a custom submit function for the form
$("form#data").submit(function(event){
//disable the default form submission
event.preventDefault();
//grab all form data
var formData = new FormData($(this)[0]);
$.ajax({
url: 'formprocessing.php',
//url: 'NombreServlet',/*Java*/
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
alert(returndata);
}
});
return false;
});
That is all that is needed to submit your "multipart/form-data" form to a PHP processing page using ajax. You would call your form data on the processing page like normal.
$id = $_POST['id'];
$username = $_POST['username'];
$profileImg = $_FILES['profileImg'];
$displayImg = $_FILES['displayImg'];
Recurso tomado de http://digipiph.com/blog/submitting-multipartform-data-using-jquery-and-ajax