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

58 comments on “jQuery Ajax submit a multipart form

  1. 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

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

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

    Reply
  4. Excelent code!

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

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

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

    Reply
  7. 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

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

      Reply
  8. Thank you very much…I have tried many tutorials…But none of worked perfectly as yours…Once again thank you very much…

    Reply
  9. Hello!
    Why is this important: processData: false, // Important!
    It seems not to work with Internet Explorer.
    Thanks.

    Reply
  10. Thanks for this great article! It really helped me.

    Reply
  11. I am getting NullPointer Exception… This is my action class… Can you please help me out?

    /*
    * To change this license header, choose License Headers in Project Properties.
    * To change this template file, choose Tools | Templates
    * and open the template in the editor.
    */
    package com.ISG.CIA.CTI.operations;

    import com.opensymphony.xwork2.ActionSupport;
    import java.io.File;
    import java.io.IOException;
    import org.apache.commons.io.FileUtils;
    //import org.apache.struts2.components.File;

    /**
    *
    * @author sachin3322
    */
    public class UploadFile extends ActionSupport {

    private File CashReqFileUpload;
    private String CashReqFileUploadFileName;
    private String CashReqFileUploadContentType;
    private String destPath;

    public String execute(){
    return SUCCESS;
    }

    public String uploadFileOnServer() throws IOException {
    destPath = “D:/Temp/”;
    // CashReqFileName = “TestFile1”;
    System.out.println(“CashReqFileUpload File name: ” + CashReqFileUpload);
    System.out.println(“CashReqFileUploadFileName File name: ” + CashReqFileUploadFileName);
    System.out.println(“destPath File Name : “+destPath);
    File destFile = new File(destPath, CashReqFileUploadFileName);
    FileUtils.copyFile(CashReqFileUpload, destFile);
    return SUCCESS;
    }

    public File getCashReqFileUpload() {
    return CashReqFileUpload;
    }

    public void setCashReqFileUpload(File CashReqFileUpload) {
    this.CashReqFileUpload = CashReqFileUpload;
    }

    public String getCashReqFileUploadFileName() {
    return CashReqFileUploadFileName;
    }

    public void setCashReqFileUploadFileName(String CashReqFileUploadFileName) {
    this.CashReqFileUploadFileName = CashReqFileUploadFileName;
    }

    public String getCashReqFileUploadContentType() {
    return CashReqFileUploadContentType;
    }

    public void setCashReqFileUploadContentType(String CashReqFileUploadContentType) {
    this.CashReqFileUploadContentType = CashReqFileUploadContentType;
    }

    public String getDestPath() {
    return destPath;
    }

    public void setDestPath(String destPath) {
    this.destPath = destPath;
    }

    }

    Reply
  12. Can you give us a ajax example without using formdata because its not working in IE8.

    Reply
  13. thank you so much…
    i was trying this for almost an hour…
    enctype: ‘multipart/form-data’ was missing from my code

    Reply
  14. This is a really cool stuff, i was stuck at upload functionality in my app but your examples has helped me a lot. 🙂

    Reply
    1. @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) {
      
      }
      Reply
  15. Hi
    How I can write my spring boot controller ? Do you give example ?

    Reply
  16. Hi mkyong and thankyou for this tutorial!!
    I did a lot o test to send a file via jQuery Ajax, including your method but I still have the same mistake: “400 Bad request”.
    This my code:

    //HTML FORM

    //JAVASCRIPT
    $(“#btnSubmit”).click(function (event) {
    event.preventDefault();
    createDatasetSync();
    });

    function createDatasetSync() {
    var form = $(‘#fileUploadForm’)[0];
    var data = new FormData(form);
    console.log(“data: “, data);
    $.ajax({
    type: ‘POST’,
    url: ”,
    beforeSend: function(xhr){
    xhr.setRequestHeader(“Authorization”, “Bearer ” + tokenJWT);
    xhr.setRequestHeader(“Content-Type”, “multipart/form-data”);
    },
    data: data,
    cache: false,
    contentType: false,
    processData: false,
    timeout: 600000,
    success: function (data) {
    console.log(data);
    },
    error: function (data) {
    console.log(“ERROR: ” , data);
    }
    });
    }

    Thanks in davance

    Reply
    1. Problem happens during multiple file upload ..working perfectly for single file….

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

    Reply
  18. 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.

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

      Reply
  19. Thanks! A really short, clear and working tutorial.

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *