jQuery Ajax submit a multipart form
A simple jQuery Ajax example to show you how to submit a multipart form, using Javascript FormData
and $.ajax()
1. HTML
A HTML form for multiple file uploads and an extra field.
<!DOCTYPE html>
<html>
<body>
<h1>jQuery Ajax submit Multipart form</h1>
<form method="POST" enctype="multipart/form-data" id="fileUploadForm">
<input type="text" name="extraField"/><br/><br/>
<input type="file" name="files"/><br/><br/>
<input type="file" name="files"/><br/><br/>
<input type="submit" value="Submit" id="btnSubmit"/>
</form>
<h1>Ajax Post Result</h1>
<span id="result"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
</body>
</html>
2. jQuery.ajax
2.1 Create a Javascript FormData
object from a form.
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
2.1 processData: false
, it prevent jQuery form transforming the data into a query string
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
processData: false, // Important!
contentType: false,
cache: false,
2.3 Full example.
$(document).ready(function () {
$("#btnSubmit").click(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
// Get form
var form = $('#fileUploadForm')[0];
// Create an FormData object
var data = new FormData(form);
// If you want to add an extra field for the FormData
data.append("CustomField", "This is some extra data, testing");
// disabled the submit button
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "/api/upload/multi",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
$("#result").text(data);
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);
},
error: function (e) {
$("#result").text(e.responseText);
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);
}
});
});
});
how to access “CustomField” on server side
Whatto do on controller. Please show that also.
What about if we have 20 extraFields?
If you use Spring Boot, you can make an object to contain them
Hi mkyong,
I’m your frequently follower and i’m grateful for the all tutorials.
One question, in jQuery, for the envents “click, ready, blur, leave, etc…” which is the best method?, I use
element.on(‘event’, function(e){}); or I should use element.event(function(e){});
Thanks.
its totally depend on situation
Suppose u r getting dynamic button value then first method (element.on(‘event’, function(e){});) will work only
Thanks! A really short, clear and working tutorial.
Really, you save me my friend!
Another great jQuery tutorial. Thank you once again.
super
Thank you. This post has been a great help for me.
this may not mean much, but this article saved my life (getting stuck in project with deadline approaching). Thank you so much for writing this up
Hi same code I have used and tried but its not working . if I upload two files its taking last file. please help me
Thank you very much! I was looking for ajax to upload zip file. Its working.
thank you ! very helpful
Thanks a lot. Keep up the good work. This saved my day
Excelent code!
It was so easy and simple, congrats for the great job posting this and THANKS so much!
JUST TO SAY THANK YOU
Excelente muchas gracias me sirvió al pelo
How to accomodate multiple files? Here he is taking only the first?
Thanks
Buen tutorial, simple y efectivo
Yes!!! Thank you!!
Thanks !!!! worked
Nice tutorial, thanks
in using jquery and ajax then how to upoad a file and get json response
Que bien que exista gente como tu, que compartes sus conocimientos, luego de varias pruebas desveladas te encontre gracias amigo por este gran tutorial. Excelente dios te bendiga sigue adelante
how to abort the ongoing ajax request ?
how to handle cors? i got invalid cors request
if you’re testing on local server like xampp, you need to disable web security in the browser.
nice
you have just saved my ass . thank you
Thank you sir
Great Post. Thank you very much.
good