1、增加依赖

<!-- https://mvnrepository.com/artifact/commons-fileupload/commonsfileupload --><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version></dependency>

2、在SpringMVC的配置文件中增加配置:

<!--必须通过文件解析器的解析能力将文件转换为MultipartFile对象--><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>

3、控制器办法:

@RequestMapping("/testUp")public String testUp(MultipartFile photo, HttpSession session)throws IOException {//获取上传的文件的文件名String fileName = photo.getOriginalFilename();//解决文件重名问题String hzName = fileName.substring(fileName.lastIndexOf("."));fileName = UUID.randomUUID().toString() + hzName;//获取服务器中photo目录的门路ServletContext servletContext = session.getServletContext();String photoPath = servletContext.getRealPath("photo");File file = new File(photoPath);if(!file.exists()){file.mkdir();}String finalPath = photoPath + File.separator + fileName;//实现上传性能photo.transferTo(new File(finalPath));return "success";}