Master Mind
Master Mind

Reputation: 2404

Ajax form submission with file upload not working Spring MVC

Ajax code:

var str = $("#observationForm").serialize();

    $.ajax({
        type : "post",
        data : str,
        url : "updateObservation",
        async : true,
/* dataType : "multipart/form-data", */
        success : function() {
            alert("success");
        }
    });

JSP-Spring Form :

<form:form modelAttribute="ObservationModal" action="updateObservation" id="observationForm">
    <label class="control-label">Tooth No</label>
    <input type="text" class="form-control" name="tooth" id="tooth" placeholder="Enter tooth no" />
    <label class="control-label">Uploaded file(PDF)</label>
    <input type="file" class="form-control" name="attachment" value="" id="attachment" placeholder="" />        
    <input type="button" value="Save" onclick="updateObservation();" />
</form:form>

Controller Class

@RequestMapping(value = "/updateObservation", method = RequestMethod.POST)
public @ResponseBody String updateObservation(
        @ModelAttribute("ObservationModal") ObservationModal formObj) {
    String result = "";

    System.out.println(":" + formObj.getTooth());
    System.out.println(formObj.getAttachment());

    return result;
}

Modal Class

public class ObservationModal implements Serializable {
    int tooth;
    private List<MultipartFile> attachment;

    public int getTooth() {
        return tooth;
    }

    public void setTooth(int tooth) {
        this.tooth = tooth;
    }

    public List<MultipartFile> getAttachment() {
        return attachment;
    }

    public void setAttachment(List<MultipartFile> attachment) {
        this.attachment = attachment;
    }

}

I can't get the values textbox values or attachment in controller. The ObservationModal is always null

Upvotes: 1

Views: 1351

Answers (3)

Shailesh Saxena
Shailesh Saxena

Reputation: 3512

For uploading a file normally you need to use encType="multipart/form-data" in your form. If you want to use Ajax to upload a file, Along with Simple ajax call you need to use its fileupload plugin. For more details have a look here: Link1, Link2, Link 3, Link 4

Upvotes: 0

Alok Pathak
Alok Pathak

Reputation: 875

A file cannot be uploaded using AJAX. To make it happen you can use formdata for fileupload but this work for only html5 supported browsers

var form = $('form')[0]; // You need to use standart javascript object here
var formData = new FormData(form);

And if you want it to work even for older browsers you can use iframe with form for fileupload.

Upvotes: 1

Darshan Lila
Darshan Lila

Reputation: 5868

To make the ajax call the url must be of the type '/projectName/actualurl'. In your case url:'/projectName/updateObservation'. And also add dataType:'text' to the call.

Upvotes: 1

Related Questions