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

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";
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理