文件上传要求form表单的请求方式必须为post,并且添加属性enctype=”multipart/form-data” SpringMVC中将上传的文件封装到MultipartFile对象中,通过此对象可以获取文件相关信息
上传步骤:
①添加依赖:
<!--文件上传需要的依赖-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
② 在SpringMVC的配置文件中添加配置:
<!--配置文件上传解析器,将上传的文件封装为MultipartFile-->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>
③控制器方法:(语法基本固定)
//文件上传
@RequestMapping("/testUp")
public String testUp(MultipartFile photo,HttpSession session) throws IOException {
String fileName = photo.getOriginalFilename();//获取上传文件的文件名
//获取上传的文件的文件名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//将UUID作为文件名
String uuid = UUID.randomUUID().toString();
//将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;
photo.transferTo(new File(finalPath));
return "success";
}
效果:(文件名为uuid)