使用Spring MVC实现上传功能,在项目开发中也是经常使用到的。例如在使用Spring MVC时,上传和Struts也有大部分相似的处理。

如图1所示,首先引入上传相关罐

 com.springsource.org.apache.commons.fileupload-1.2.0.jar

com.springsource.org.apache.commons.io-1.4.0.jar

2,编写前台JSP代码

【JAVA]   查看纯 字幕:  
  1. <BODY>  
  2.    <form action = “test / upload.do”  method = “post”  enctype = “multipart / form-data” >  
  3.     图:<input type = “file”  name = “pic” > <br>  
  4.     <input type = “submit”  value = “submit” > <br>  
  5.    </ FORM>  
  6.  </ BODY>  

3,后台上传代码

【JAVA]   查看纯 字幕:  
  1. @RequestMapping (value = “/upload.do” )  
  2.     public  String upload(Person person,HttpServletRequest request)  throws  Exception {  
  3.         //第一步转化请求  
  4.         MultipartHttpServletRequest rm =(MultipartHttpServletRequest)请求;  
  5.         //获得文件  
  6.         CommonsMultipartFile cfile =(CommonsMultipartFile)rm.getFile(“pic” );  
  7.         //获得文件的字节数组       
  8.         byte [] bfile = cfile.getBytes();  
  9.         String fileName = “”;  
  10.         //获得当前时间的最小精度  
  11.         SimpleDateFormat format =  new SimpleDateFormat(“yyyyMMddHHmmssSSS”);  
  12.         fileName = format.format(new Date());  
  13.         //获得三位随机数  
  14.         随机随机=  随机();  
  15.         forint i = 0; i < 3; i ++){  
  16.             fileName = fileName + random.nextInt(9);  
  17.         }  
  18.         //获得原始文件名  
  19.         String origFileName = cfile.getOriginalFilename();  
  20.         //XXX.jpg  
  21.         字符串后缀= origFileName.substring(origFileName.lastIndexOf(“。”));  
  22.         //拿到项目的部署路径  
  23.         String path = request.getSession()。getServletContext()。getRealPath(“/” );  
  24.         //定义文件的输出流  
  25.         OutputStream out =  new  FileOutputStream(new  File(path + “/ upload /” + fileName + suffix));  
  26.         out.write(BFILE);  
  27.         了了out.flush();  
  28.         out.close();  
  29.         返回“/ index” ;   
  30.     }