Spring MVC 上下文中默认没有为文件上传提供了直接的支持,因 此默认情况下不能处理文件的上传工作,如果想使用 Spring 的文件上传功能,需现在上下文中配置 CommonsMultipartResovler:
1.加入jar包:
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
2.在SpringMVC配置文件中配置CommonsMultipartResovler
<!-- 配置CommonsMultipartResolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="defaultEncoding" value="utf-8"></property> <!-- 以字节为单位 --> <property name="maxUploadSize" value="1024000"></property> </bean>
注意:id="multipartResolver"不可省略,id值multipartResolver为默认值,一般不可修改。
3.表单:POST请求,file类型,enctype="multipart/form-data"
文件上传
1 @RequestMapping(value="testUpload",method=RequestMethod.POST) 2 public String testUpload(HttpServletRequest request,@RequestParam(value="desc",required=false) String desc,@RequestParam("photo") CommonsMultipartFile file) throws Exception{ 3 ServletContext servletContext = request.getServletContext(); 4 String realPath = servletContext.getRealPath("/upload"); 5 File file1 = new File(realPath); 6 if(!file1.exists()){ 7 file1.mkdir(); 8 } 9 OutputStream out; 10 InputStream in; 11 //uuid_name.jpg 12 String prefix = UUID.randomUUID().toString(); 13 prefix = prefix.replace("-",""); 14 String fileName = prefix+"_"+file.getOriginalFilename(); 15 System.out.println(fileName); 16 17 out = new FileOutputStream(new File(realPath+"\"+fileName)); 18 in = file.getInputStream(); 19 IOUtils.copy(in, out); 20 out.close(); 21 in.close(); 22 23 return "success"; 24 }
将上面文件代码中的IOUtils.copy(in, out);用下面代码代替,即变为原生文件上传: 代码1: byte[] buffer=new byte[in.available()]; in.read(buffer); out.write(buffer);//不适合传送量大 代码2: byte[] buffer=new byte[1024]; int len; while ((len=in.read(buffer))!=-1) { out.write(buffer, 0, len); out.flush(); }