关于spring-mvc:SpringMVC使用MultipartFile对象实现文件上传

2次阅读

共计 966 个字符,预计需要花费 3 分钟才能阅读完成。

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.CommonsMultipartRe
solver">
</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";
}
正文完
 0