添加文件上传相关依赖
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.3</version> </dependency>
配置文件上传解析器(CommonsMultipartResolver)
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 --> <property name="defaultEncoding" value="UTF-8"></property> <!-- 文件最大大小(字节) 1024*1024*50=50M--> <property name="maxUploadSize" value="52428800"></property> <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常--> <property name="resolveLazily" value="true"/> </bean>
表单提交方式为method="post"
<form action="/book/upload" method="post" enctype="multipart/form-data"> 请选择文件:<input type="file" name="axc"/> <input type="submit" value="确认"> </form>
文件项用spring提供的MultipartFile进行接收
@RequestMapping("/upload") public String upload(HttpServletRequest req, MultipartFile axc) { String fileName=axc.getOriginalFilename(); String ContentType=axc.getContentType(); try { FileUtils.copyInputStreamToFile(axc.getInputStream(),new File("E:/mabatis/"+fileName)); } catch (IOException e) { e.printStackTrace(); } return "redirect:/book/list"; }