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>

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

ok but i want to do it without annotations ... How can i do that ?
Please see this question for configuration without annotations. You have to use request.getInputStream() in this case. However, I would recommend annotation configuration.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.