SpringMVC:文件上传
1.配置SpringMVC的文件上传解析器
文件上传form的请求方式必须为post,并且添加属性enctype="multipart/form-data"
<form th:action="@{/testup}" method="post" enctype="multipart/form-data">
头像:<input type="file" name="photo">
<input type="submit" value="上传">
</form>
添加依赖:
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息
在SpringMVC配置文件中添加配置
<!--配置文件上传解析器,将上传的文件封装为MultipartFile-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>
2.实现文件上传功能
//文件上传
@RequestMapping("/testup")
public String testup(MultipartFile photo,HttpSession session) throws IOException {
String fileName = photo.getOriginalFilename();
ServletContext servletContext = session.getServletContext();
String photoPath = servletContext.getRealPath("photo");
File file = new File(photoPath);
//判断photoPath 所对应的路径是否存在
if(!file.exists()){
//如果不存在就创建
file.mkdir();
}
String finalPath = photoPath + File.separator + fileName; //File.separator 为文件的分隔符
photo.transferTo(new File(finalPath));
return "success";
}
3.解决文件的重名问题:
将上传的文件的文件名修改为uuid
//文件上传
@RequestMapping("/testup")
public String testup(MultipartFile photo,HttpSession session) throws IOException {
//获取上传的文件的文件名
String fileName = photo.getOriginalFilename();
//获取上传文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//将UUID作为文件名 replaceAll 为替换uuid中的“-”
String uuid = UUID.randomUUID().toString().replaceAll("-","");
//将UUID和后缀名拼接后的结果作为最终的文件名
fileName = uuid + suffixName ;
//通过ServletContext获取服务器中photo目录的路径
ServletContext servletContext = session.getServletContext();
String photoPath = servletContext.getRealPath("photo");
File file = new File(photoPath);
//判断photoPath 所对应的路径是否存在
if(!file.exists()){
//如果不存在就创建
file.mkdir();
}
String finalPath = photoPath + File.separator + fileName; //File.separator 为文件的分隔符
photo.transferTo(new File(finalPath));
return "success";
}
阅读剩余
版权声明:
作者:Tin
链接:http://www.tinstu.com/1194.html
文章版权归作者所有,未经允许请勿转载。
THE END