3

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>
Amit Das
  • 1,077
  • 5
  • 17
  • 44

1 Answers1

6

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);
Constantine
  • 3,187
  • 20
  • 26
  • ok but i want to do it without annotations ... How can i do that ? – Amit Das Aug 05 '15 at 13:55
  • Please see [this question](http://stackoverflow.com/questions/9991519/spring-mvc-3-1-without-annotations) for configuration without annotations. You have to use `request.getInputStream()` in this case. However, I would recommend annotation configuration. – Constantine Aug 13 '15 at 01:36