November 20, 2015

Upload file using ajax file upload and spring mvc

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

Reference:
http://stackoverflow.com/questions/31832169/how-to-upload-file-using-ajax-file-upload-and-spring-mvc

No comments:

Post a Comment

I'm certainly not an expert, but I'll try my hardest to explain what I do know and research what I don't know.

My Favorite Site's List

#update below script more than 500 posts