引入依赖包:
<!-- 文件上传的依赖 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency>
配置文件上传解析器:
<!--定义文件上传解析器--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--设定默认编码--> <property name="defaultEncoding" value="UTF-8"></property> <!--设定上传文件的最大值 5M--> <property name="maxUploadSize" value="5242880"></property> </bean>
编写上传文件controller:
//上传文件 @RequestMapping("/uploadFile") public ModelAndView uploadFile(@RequestParam("file") MultipartFile file) throws IOException { ModelAndView mv = new ModelAndView("xxx"); if (file != null) { //将上传的文件放到服务器指定位置 file.transferTo(new File("D:/uploadFiles/" + file.getOriginalFilename())); } mv.addObject("msg", "上传成功!"); return mv; }