使用Spring MVC实现上传功能,在项目开发中也是经常使用到的。例如在职工入职时,ERP系统便会需要上传员工照片。使用Spring MVC的上传和Struts也有大部分相似之处。
1、首先引入上传相关jar
com.springsource.org.apache.commons.fileupload-1.2.0.jar
com.springsource.org.apache.commons.io-1.4.0.jar
2、编写前台jsp代码
<body>
<form action="test/upload.do" method="post" enctype="multipart/form-data">
pic:<input type="file" name="pic"><br>
<input type="submit" value="submit"><br>
</form>
</body>
3、后台上传代码
@RequestMapping(value="/upload.do")
public String upload(Person person,HttpServletRequest request) throws Exception{
//第一步转化request
MultipartHttpServletRequest rm = (MultipartHttpServletRequest) request;
//获得文件
CommonsMultipartFile cfile = (CommonsMultipartFile) rm.getFile("pic");
//获得文件的字节数组
byte[] bfile = cfile.getBytes();
String fileName = "";
//获得当前时间的最小精度
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
fileName = format.format(new Date());
//获得三位随机数
Random random = new Random();
for(int i = 0; i < 3; i++){
fileName = fileName + random.nextInt(9);
}
//获得原始文件名
String origFileName = cfile.getOriginalFilename();
//XXX.jpg
String suffix = origFileName.substring(origFileName.lastIndexOf("."));
//拿到项目的部署路径
String path = request.getSession().getServletContext().getRealPath("/");
//定义文件的输出流
OutputStream out = new FileOutputStream(new File(path+"/upload/"+fileName+suffix));
out.write(bfile);
out.flush();
out.close();
return "/index";
}