第一步 导jar
commons-fileupload-1.3.3.jar
相关pom描述文件
<!--文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
第二步 配置文件
springmvc.xml里配置文件上传解析器
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- one of the properties available; the maximum file size in bytes -->
<property name="maxUploadSize" value="1024000"/>
</bean>
第三步 写前后台
前台
<form method="post" action="<%=request.getContextPath()%>/file/upload.action" enctype="multipart/form-data">
真实姓名:<input type="text" name="userName"/>
头像:<input type="file" name="file"><br>
<input type="submit"/>
</form>
后台
建文件夹images/upload
public class UUIDGenerateUtil {
public static String getUUID(){
return UUID.randomUUID().toString().replaceAll("-", "");
}
}
@RequestMapping("/upload")
public String fileUpload(MultipartFile file,String userName,HttpServletRequest request){
System.out.println("文件到达后台");
//要把文件存储到服务器 images/upload
//首先要拿到/images/upload的绝对路径
//e:/tomcat/images/upload /home/tomcat/images/upload
String path= request.getRealPath("/images/upload");
//生成文件名
//从用户传过来的file里可以拿到原始文件名,然后我们给他加上唯一标识,合成一个不会重复的文件名
String uuid=UUIDGenerateUtil.getUUID();
String old_file=file.getOriginalFilename();
String new_filename=uuid+old_file;
File f=new File(path,new_filename);
try {
//文件持久化
file.transferTo(f);
//拼装一个user对象,持久化到数据库表(包括头像文件名)
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute("filename", new_filename);
return "index";
}
Index.jsp
<img src="<%=request.getContextPath()%>/images/upload/${filename}"/>