SpringMVC实现文件上传功能
文件上传
文件上传要求form表单的请求方式必须为post,并且添加属性enctype="multipart/form-data"
SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息
缺一不可
1.请求方式必须为post
2.属性enctype="multipart/form-data"
上传步骤:
a>添加依赖:
commons-fileupload
commons-fileupload
1.3.1
b>在SpringMVC的配置文件中添加配置:
c>控制器方法:
/**
* 实现文件上传功能
* @param photo
* @param session
* @return
* @throws IOException
*/
@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);
//如果服务器中不存在photo路径,则创建一个
if(!file.exists()){
file.mkdir();
}
//最终的上传路径
//File.separator 文件分隔符/
String finalPath = photoPath + File.separator + fileName;
//实现上传功能
photo.transferTo(new File(finalPath));
return "target";
}
d>html代码
上传测试
测试


上传成功