From yeasterday i'm trying to upload file by ajax to my Spring application. This is my Controller:
@RequestMapping(value="/upload", method=RequestMethod.POST)
@ResponseBody
public String uploadFile(
@RequestParam("file") MultipartFile file, Principal principal )
{
if( principal != null ) {
}
return "";
}
form in html code:
<form id="uploadImageForm"
name="uploadImageForm"
enctype="multipart/form-data">
<div class='dialog' style='width:200px;'>
<div class='green_button' id='files' name='files'>
<div class='green_button_text' id="add_image">
wybierz zdjęcie
</div>
<input type="file" name="file" id="fileInputHidden" style="display:none"/>
</div>
<script>
$("#add_image").click(function(){
$("input[id='fileInputHidden']").click();
});
</script>
</div>
</form>
Script to send file by ajax:
document.getElementById('fileInputHidden').addEventListener('change', this.onFileChange, false);
},
this.onFileChange = function( evt ) {
var file = evt.target.files[0];
if( !file != null ) {
if (!!file.type.match(/image.*/)) {
$( document.forms['uploadImageForm'] ).ajaxUpload( {
url: CONTEXT_URL + "/upload",
method: "POST",
success: function(response) {
$("#accept").css("opacity","1");
$("#accept").click(function(){
$("#ac").css("display","none");
});
}
});
} else {
alert("Wybrany plik nie jest zdjęciem!");
}
}
in dispacher-servlet.xml added CommonsMultipartResolver bean.
when jquery send ajax post request, get Internal error (500) and my stack looks like:
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/jadenazlot] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: Expected MultipartHttpServletRequest: is a MultipartResolver configured?] with root cause
java.lang.IllegalArgumentException: Expected MultipartHttpServletRequest: is a MultipartResolver configured?
at org.springframework.util.Assert.notNull(Assert.java:112)
at org.springframework.web.method.annotation.RequestParamMethodArgumentResolver.resolveName(RequestParamMethodArgumentResolver.java:161)
at org.springframework.web.method.annotation.AbstractNamedValueMethodArgumentResolver.resolveArgument(AbstractNamedValueMethodArgumentResolver.java:86)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:79)
I tryied to change @RequestParam annotation to
String uploadFileHandler(@ModelAttribute("uploadImageForm") UploadedFile file ) {/*...*/}
Uploaded file is my own class with getter and setter but, then i'm get NullPointerExcepotions in file.getFile()
What i'm doing wrong?
MultipartResolver have to set maxUploadSize.
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="50000000"/>
</bean>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With