How to upload a file using ajax file upload and spring mvc?
I have a jsp file in which I upload a file using the ajax file upload method. To handle the backend of the file, I made a contoller in spring. But I couldn't find how I can process the file in spring 2.5 in this state? 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>
+3
source to share
1 answer
There are two main steps:
1) add a multipart resolver instance to your 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 java.io.File
from org.springframework.web.multipart.MultipartFile
:
File file = new File("my-file.txt");
multipartFile.transferTo(file);
+4
source to share