从昨天开始,我正在尝试通过ajax将文件上传到我的Spring
应用程序。这是我的控制器:
@RequestMapping(value="/upload", method=RequestMethod.POST)
@ResponseBody
public String uploadFile(
@RequestParam("file") MultipartFile file, Principal principal )
{
if( principal != null ) {
}
return "";
}
以html代码形式:
<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>
通过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!");
}
}
在dispacher-servlet.xml中添加了CommonsMultipartResolver
bean。
当jquery发送ajax post请求时,得到内部错误(500),我的堆栈看起来像:
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)
我试图将@RequestParam注释更改为
String uploadFileHandler(@ModelAttribute("uploadImageForm") UploadedFile file ) {/*...*/}
上传的文件是我自己的getter和setter类,但是我在file.getFile()
中得到NullPointerExcepotions
我做错了什么?
答案 0 :(得分:11)
MultipartResolver必须设置maxUploadSize。
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="50000000"/>
</bean>