How to upload file using ajax file upload and spring mvc?

23,557

There are two main steps:

1) add an instance of multipart resolver to the Spring context

<bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

2) add a handler method

// I assume that your controller is annotated with /ajaxSaveMedia.do
@RequestMapping(method = RequestMethod.POST)
public @ResponseBody String doUpload(@RequestParam("file") MultipartFile multipartFile) {                 
    return "Uploaded: " + multipartFile.getSize() + " bytes";
}

To get an instance of java.io.File from org.springframework.web.multipart.MultipartFile:

File file = new File("my-file.txt");
multipartFile.transferTo(file);
Share:
23,557
Amit Das
Author by

Amit Das

A Java-J2EE Programmer, love coding and solving others problems

Updated on June 20, 2020

Comments

  • Amit Das
    Amit Das about 4 years

    I have a jsp file in which i am uploading a file using ajax file upload method. For backend handling of file i made a contoller in spring. But i could not find that how can i handle file in spring 2.5 in this condition ? My Code is -

    JSP FILE

    <input type="file" name="file" />
    <script type="text/javascript">
            function saveMedia() {
                var formData = new FormData();
                formData.append('file', $('input[type=file]')[0].files[0]);
                console.log("form data " + formData);
                $.ajax({
                    url : 'ajaxSaveMedia.do',
                    data : formData,
                    processData : false,
                    contentType : false,
                    type : 'POST',
                    success : function(data) {
                        alert(data);
                    },
                    error : function(err) {
                        alert(err);
                    }
                });
            }
        </script>