Main Tutorials

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

            }
        });

    });

});

References

  1. jQuery.ajax()
  2. MDN – Using FormData Objects
  3. Spring Boot file upload example – Ajax and REST

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
57 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
suman singh
5 years ago

how to access “CustomField” on server side

Azhar
6 years ago

Whatto do on controller. Please show that also.

Guest
4 years ago
Reply to  Azhar
@RequestMapping(value = "/file/upload", method = RequestMethod.POST)
@ResponseBody
public ResultData upload(
        @RequestParam(value = "extraField1", required = false) String extraField1,
        @RequestParam(value = "extraField2", required = false) String extraField2,
        @RequestParam(value = "file_1") MultipartFile files,
        HttpServletRequest request) {

}
SHIVA
4 years ago
Reply to  Guest

What about if we have 20 extraFields?

Arya
3 years ago
Reply to  SHIVA

If you use Spring Boot, you can make an object to contain them

MG_Bautista
6 years ago

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.

awais
3 years ago
Reply to  MG_Bautista

its totally depend on situation
Suppose u r getting dynamic button value then first method (element.on(‘event’, function(e){});) will work only

aristipp
6 years ago

Thanks! A really short, clear and working tutorial.

Ricardo
6 years ago

Really, you save me my friend!

Lana
6 years ago

Another great jQuery tutorial. Thank you once again.

karthi
4 years ago
Reply to  Lana

super

ThankYou!
6 years ago

Thank you. This post has been a great help for me.

Adrian
10 months ago

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

Girish
1 year ago

Hi same code I have used and tried but its not working . if I upload two files its taking last file. please help me

Asif
1 year ago

Thank you very much! I was looking for ajax to upload zip file. Its working.

abhishek
1 year ago

thank you ! very helpful

R.A
2 years ago

Thanks a lot. Keep up the good work. This saved my day

Harlem
2 years ago

Excelent code!

It was so easy and simple, congrats for the great job posting this and THANKS so much!

KOFI
3 years ago

JUST TO SAY THANK YOU

Johban Clavijo
3 years ago

Excelente muchas gracias me sirvió al pelo

cp anon
3 years ago

How to accomodate multiple files? Here he is taking only the first?

Ulrich
3 years ago

Thanks

Diego
3 years ago

Buen tutorial, simple y efectivo

Matheus Afonso
3 years ago

Yes!!! Thank you!!

Daniel
4 years ago

Thanks !!!! worked

Pablo
4 years ago

Nice tutorial, thanks

Hardik
4 years ago

in using jquery and ajax then how to upoad a file and get json response

Jefferson Vasconez
4 years ago

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

Priyanka Bhale
4 years ago

how to abort the ongoing ajax request ?

Jhon
4 years ago

how to handle cors? i got invalid cors request

Hari Krishna
2 years ago
Reply to  Jhon

if you’re testing on local server like xampp, you need to disable web security in the browser.

abilio.vida
4 years ago

nice

Nail
4 years ago

you have just saved my ass . thank you

pubudu sachintha
4 years ago

Thank you sir

Andrew Krenitz
4 years ago

Great Post. Thank you very much.

alfred
5 years ago

good