spring 封装了文件上传功能,使用spring mvc上传文件需要完成下面的工作:
1. 配置MultipartFileResolver
在spring容器中注入MultipartFileResolver bean
<bean id="commonsMultipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"/> <property name="maxInMemorySize" value="1073741824"/> <property name="maxUploadSize" value="50000000"/> </bean>
应用该功能需要apche的commons-fileupload和commons-io依赖,因为它们提供底层api,spring是对它们的一种封装
2. jsp文件创建表单
<form id="upload_form" action="/upload/example" method="post" enctype="multipart/form-data" onsubmit="return sub();" > <textarea rows="4" name="description" class="form-control ng-pristine ng-valid ng-touched" placeholder="填写something"></textarea> <span class="gray weight">上传歌曲:</span><input id="target_file" name="file" type="file" /> <button id="submit_btn" class="inputBtn">确定上传</button> </form> <script type="text/javascript"> function sub() {//简单的验证 var file = $("#week_song_file").val(); if(file==null||file.indexOf(".mp3")==-1){ alert("请选择mp3格式的文件"); return false; } return true; } </script>
文件的提交有其它方式,比如ajax或jquery的上传插件,这里只做示例
3. controller中文件上传处理
@Controller public class UploadController { @Autowired MultipartResolver resolver; @RequestMapping(value="/member/{uid}/weeksong/upload",method = RequestMethod.POST) @ResponseBody public String upload(@PathVariable long uid,HttpSession session,HttpServletRequest request){ String result="ok"; if(resolver.isMultipart(request)){ MultipartHttpServletRequest multipartRequest=resolver.resolveMultipart(request); MultipartFile file=multipartRequest.getFile("file");//此处文件名字‘file’要于表单中提交的一致 String description=multipartRequest.getParameter("description"); //处理file.... } }else{ result="type error"; } return result; } }
接收文件的方法中有另一种方式:
@RequestMapping(value="/member/{uid}/weeksong/upload",method = RequestMethod.POST) @ResponseBody public String upload(@PathVariable long uid,HttpSession session,@RequestParam("file")MultipartFile file,@RequestParam String description){ //handle file... }
直接将上传的文件以变量的形式封装到一个MultipartFile类型的对象file中,这是出现错误:java.lang.IllegalArgumentException: Expected MultipartHttpServletRequest: is a MultipartResolver configured? 具体原因还要研究一下