现在的位置: 首页 > 综合 > 正文

通过SpringMVC进行文件的上传

2014年09月05日 ⁄ 综合 ⁄ 共 14325字 ⁄ 字号 评论关闭

还是直接上例子来说明:

1. 配置好web.xml

[html] view
plain
copy

  1.  <servlet>  
  2.         <servlet-name>smartcity-upload</servlet-name>  
  3.     <servlet-class>  
  4.         org.springframework.web.servlet.DispatcherServlet  
  5.     </servlet-class>  
  6.     <init-param>    
  7.               <param-name>contextConfigLocation</param-name>    
  8.             <param-value>/WEB-INF/config/spring-smartcity/smartcity-upload-servlet.xml</param-value>    
  9.             </init-param>    
  10.         <load-on-startup>1</load-on-startup>  
  11. </servlet>  
  12. <servlet-mapping>  
  13.         <servlet-name>smartcity-upload</servlet-name>  
  14.         <url-pattern>/uploadFile.action</url-pattern>  
  15. </servlet-mapping>  

2. 配置好smartcity-upload-servlet.xml

[html] view
plain
copy

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"  
  5.     default-lazy-init="true">  
  6.       
  7.     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  8.         <!-- set the max upload size10MB -->  
  9.         <property name="maxUploadSize">  
  10.             <value>10485760</value>  
  11.         </property>  
  12.     </bean>  
  13.       
  14.     <bean name="fileUploadController" autowire-candidate="false" class="cn.ffcs.smartcity.cbusiness.web.action.FileUploadController">  
  15.         <property name="commandClass" value="java.lang.Object" />  
  16.         <property name="uploadDir">  
  17.             <value>${uploadDir}</value>  
  18.         </property>  
  19.     </bean>  
  20.       
  21.     <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">  
  22.       <property name="mappings">  
  23.           <props>  
  24.           <prop key="/uploadFile.action">  
  25.                  fileUploadController  
  26.           </prop>  
  27.        </props>  
  28.       </property>  
  29.      </bean>  
  30.       
  31. </beans>  

3. 在配置文件中加载properties文件中的参数代码如下:

[html] view
plain
copy

  1. <bean id="propertyConfigurer_city"  
  2.     class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  3.     <property name="order" value="2" />  
  4.     <property name="ignoreUnresolvablePlaceholders" value="true" />  
  5.     <property name="location">  
  6.         <value>classpath:/config.properties</value>  
  7.     </property>  
  8. </bean>  


4. 主体文件上传类

[java] view
plain
copy

  1. package cn.ffcs.smartcity.cbusiness.web.action;  
  2.   
  3. import java.awt.geom.AffineTransform;  
  4. import java.awt.image.AffineTransformOp;  
  5. import java.awt.image.BufferedImage;  
  6. import java.io.File;  
  7. import java.io.IOException;  
  8. import java.util.ArrayList;  
  9. import java.util.Iterator;  
  10. import java.util.List;  
  11. import java.util.Random;  
  12.   
  13. import javax.imageio.ImageIO;  
  14. import javax.servlet.http.HttpServletRequest;  
  15. import javax.servlet.http.HttpServletResponse;  
  16.   
  17. import org.springframework.validation.BindException;  
  18. import org.springframework.web.multipart.MultipartFile;  
  19. import org.springframework.web.multipart.MultipartHttpServletRequest;  
  20. import org.springframework.web.servlet.ModelAndView;  
  21. import org.springframework.web.servlet.mvc.SimpleFormController;  
  22. import cn.ffcs.smartcity.cbusiness.om.vo.FileUploadVO;  
  23. import cn.ffcs.smartcity.constants.CodeConstants;  
  24. import cn.ffcs.smartcity.constants.UploadFilePathConstants;  
  25. import cn.ffcs.smartcity.inner.vo.Exter;  
  26. import cn.ffcs.smartcity.util.PropertiesUtil;  
  27.   
  28. public class FileUploadController extends SimpleFormController {  
  29.   
  30.     private final static String CHARSET = "utf-8";  
  31.     private final static int THUMBNAIL_PIXEL = 100;  
  32.     private String uploadDir;  
  33.       
  34.     protected ModelAndView onSubmit(HttpServletRequest request,  
  35.             HttpServletResponse response, Object cmd, BindException errors)  
  36.             throws Exception {  
  37.           
  38.         //获取上传文件的业务类型  
  39.         String businessType = request.getParameter("businessType");  
  40.         String result = "";  
  41.         if(businessType != null && !"".equals(businessType)) {  
  42.             //根据业务类型获取上传的路径  
  43.             String path = this.getPathByBusinessType(businessType);  
  44.             //上传文件  
  45.             FileUploadVO fileUploadVO = uploadFile(request,path);  
  46.             //根据业务类型判断是否有其他操作  
  47.             fileUploadVO.setBusinessType(businessType);  
  48.             fileUploadVO = this.doOtherOper(fileUploadVO);  
  49.               
  50.             result = this.getResultString(fileUploadVO);  
  51.         } else {  
  52.             //如果业务类型为空时,返回提示信息  
  53.             result = "传递的businessType信息为空,上传失败.";  
  54.         }  
  55.         //返回客户端一些相关信息  
  56.         response = this.getResponse(response, result, CHARSET);  
  57.         return null;  
  58.     }  
  59.   
  60.     private FileUploadVO uploadFile(HttpServletRequest request,String path) throws IOException {  
  61.         // 转型为MultipartHttpRequest:  
  62.         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;  
  63.         String originalFileName = "";  
  64.         String fileName = "";  
  65.         String fileType = "";  
  66.         FileUploadVO fileUploadVO = null;  
  67.         // 遍历所有文件域,获得上传的文件  
  68.         for (Iterator it = multipartRequest.getFileNames(); it.hasNext();) {  
  69.             String key = (String) it.next();  
  70.             MultipartFile file = multipartRequest.getFile(key);  
  71.             if (file == null || file.isEmpty())  
  72.                 continue;  
  73.             originalFileName = file.getOriginalFilename();  
  74.             fileType = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);  
  75.             //检查上传文件的类型  
  76.             if(!this.checkCommenFileType(fileType)) {  
  77.                 throw new IOException("传递的文件类型错误,类型为:" + fileType);  
  78.             }  
  79.             fileName = System.currentTimeMillis() +"_" + new Object().hashCode()+ new Random().nextLong() + "." + fileType;  
  80.             saveFile(file,path,fileName);  
  81.               
  82.             //上传成功,记录对应的信息  
  83.             fileUploadVO = new FileUploadVO();  
  84.             fileUploadVO.setFilePath(path + fileName);  
  85. //          fileUploadVO.setUploadDir(uploadDir);  
  86.         }  
  87.         return fileUploadVO;  
  88.     }  
  89.   
  90.     private void saveFile(MultipartFile file,String path,String fileName) throws IOException {  
  91.           
  92.         File filePath = new File(uploadDir + path);  
  93.         if(!filePath.exists()) {  
  94.             filePath.mkdirs();  
  95.         }  
  96.         String localfileName = uploadDir + path + fileName;  
  97.         // 写入文件  
  98.         File fileAbsolutePath = new File(localfileName.toString());  
  99.         if(!fileAbsolutePath.exists()) {  
  100.             fileAbsolutePath.createNewFile();  
  101.         }  
  102.         //开始上传文件  
  103.         file.transferTo(fileAbsolutePath);  
  104.     }  
  105.       
  106.     private FileUploadVO uploadThumbnailFile(FileUploadVO fileUploadVO) throws IOException {  
  107.           
  108.         //获取大图片的文件地址  
  109.         String bigPicFilePath = uploadDir + fileUploadVO.getFilePath();  
  110.         File bigPicFile = new File(bigPicFilePath);  
  111.         //创建一个缩略图的文件  
  112.         File file = new File(uploadDir + fileUploadVO.getUploadPath());  
  113.         if(!file.exists()) {  
  114.             file.mkdirs();  
  115.         }  
  116.           
  117.         String fileType = bigPicFilePath.substring(bigPicFilePath.lastIndexOf(".") + 1);  
  118.         //检查上传文件的类型  
  119.         if(!this.checkSpecialFileType(fileType)) {  
  120.             throw new IOException("传递的文件类型错误,类型为:" + fileType);  
  121.         }  
  122.         String fileName = System.currentTimeMillis() +"_" + new Object().hashCode()+ new Random().nextLong() + "." +  fileType;  
  123.         String smallPicPath = uploadDir + fileUploadVO.getUploadPath()  + fileName;  
  124.         /* 创建文件流信息 */  
  125.         File smallPicFile = new File(smallPicPath);  
  126.         if (!smallPicFile.exists()) {  
  127.             smallPicFile.createNewFile();  
  128.         }  
  129.           
  130.         //以下为生成缩略图的方法  
  131.         AffineTransform transform = new AffineTransform();  
  132.         BufferedImage bis = ImageIO.read(bigPicFile);  
  133.   
  134.         int w = bis.getWidth();  
  135.         int h = bis.getHeight();  
  136.         double scale = (double)w/h;  
  137.         int nw = THUMBNAIL_PIXEL;  
  138.         int nh = (nw * h) / w;  
  139.         if(nh > THUMBNAIL_PIXEL) {  
  140.             nh = THUMBNAIL_PIXEL;  
  141.             nw = (nh * w) / h;  
  142.         }  
  143.         double sx = (double)nw / w;  
  144.         double sy = (double)nh / h;  
  145.         transform.setToScale(sx,sy);  
  146.         AffineTransformOp ato = new AffineTransformOp(transform, null);  
  147.         BufferedImage bid = new BufferedImage(nw, nh,BufferedImage.TYPE_3BYTE_BGR);  
  148.         ato.filter(bis, bid);  
  149.         ImageIO.write(bid, fileType, smallPicFile);  
  150.           
  151.         //设置好缩略图的地址  
  152.         fileUploadVO.setThumbnailFilePath(fileUploadVO.getUploadPath()  + fileName);  
  153.         return fileUploadVO;  
  154.     }  
  155.       
  156.     private FileUploadVO doOtherOper(FileUploadVO fileUploadVO) throws IOException {  
  157.           
  158.         if(fileUploadVO != null) {  
  159.             if(CodeConstants.S_BUSINESSTYPE_UNISERVALPHOTO.equals(fileUploadVO.getBusinessType())) {  
  160.                 //判断是随手拍大图片上传之后,开始进行缩略图的压缩上传  
  161.                 //设置缩略图上传的相对路径       
  162.                 fileUploadVO.setUploadPath(UploadFilePathConstants.UNIVERSAL_SMALL_PHOTO_PATH);  
  163.                 fileUploadVO = this.uploadThumbnailFile(fileUploadVO);  
  164.             }  
  165.         }  
  166.           
  167.         return fileUploadVO;  
  168.     }  
  169.       
  170.     private String getPathByBusinessType(String businessType) {  
  171.           
  172.         String path = UploadFilePathConstants.UPLOAD_FILE_DEFAULT_PATH;  
  173.         if(CodeConstants.S_BUSINESSTYPE_UNISERVALPHOTO.equals(businessType)) {  
  174.             path = UploadFilePathConstants.UNIVERSAL_BIG_PHOTO_PATH;  
  175.         }  
  176.           
  177.         return path;  
  178.     }  
  179.       
  180.     private String getResultString(FileUploadVO fileUploadVO) {  
  181.           
  182.         StringBuffer sb = new StringBuffer();  
  183.         if(fileUploadVO != null) {  
  184.             if(fileUploadVO.getFilePath() != null && !"".equals(fileUploadVO.getFilePath())) {  
  185.                 sb.append(fileUploadVO.getFilePath()).append(",");  
  186.             }  
  187.             if(fileUploadVO.getThumbnailFilePath() != null && !"".equals(fileUploadVO.getThumbnailFilePath())) {  
  188.                 sb.append(fileUploadVO.getThumbnailFilePath()).append(",");  
  189.             }  
  190.               
  191.         }  
  192.         return sb.toString();  
  193.     }  
  194.   
  195.     private boolean checkCommenFileType(String fileType){  
  196.         boolean result = false;  
  197.         if(fileType != null) {  
  198.             fileType = fileType.toUpperCase();  
  199.             if("JPG".equals(fileType) || "PNG".equals(fileType) || "GIF".equals(fileType)  
  200.                     || "DOC".equals(fileType) || "DOCS".equals(fileType) || "XLS".equals(fileType) || "XLSX".equals(fileType)  
  201.                     || "PDF".equals(fileType)) {  
  202.                 result = true;  
  203.             }  
  204.         }  
  205.         return result;  
  206.     }  
  207.       
  208.     private boolean checkSpecialFileType(String fileType){  
  209.         boolean result = false;  
  210.         if(fileType != null) {  
  211.             fileType = fileType.toUpperCase();  
  212.             if("JPG".equals(fileType) || "PNG".equals(fileType) || "GIF".equals(fileType)) {  
  213.                 result = true;  
  214.             }  
  215.         }  
  216.         return result;  
  217.     }  
  218.       
  219.     private HttpServletResponse getResponse(HttpServletResponse response,String msg,String charset) throws IOException {  
  220.           
  221.         if(msg != null && !"".equals(msg)) {  
  222.             byte[] bt = msg.getBytes(charset);  
  223.             response.getOutputStream().write(bt);  
  224.         }  
  225.         return response;  
  226.     }  
  227.   
  228.     public String getUploadDir() {  
  229.         return uploadDir;  
  230.     }  
  231.   
  232.     public void setUploadDir(String uploadDir) {  
  233.         this.uploadDir = uploadDir;  
  234.     }  
  235.       
  236. }  


5. 以下为测试该上传方法的单测类

[java] view
plain
copy

  1. package url;  
  2.   
  3. import io.IoStreamUtil;  
  4.   
  5. import java.io.File;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.nio.charset.Charset;  
  9.   
  10. import org.apache.commons.httpclient.params.HttpMethodParams;  
  11. import org.apache.http.HttpEntity;  
  12. import org.apache.http.HttpResponse;  
  13. import org.apache.http.client.ClientProtocolException;  
  14. import org.apache.http.client.HttpClient;  
  15. import org.apache.http.client.methods.HttpPost;  
  16. import org.apache.http.entity.mime.MultipartEntity;  
  17. import org.apache.http.entity.mime.content.FileBody;  
  18. import org.apache.http.entity.mime.content.StringBody;  
  19. import org.apache.http.impl.client.DefaultHttpClient;  
  20.   
  21. /** 
  22.  * httpclient上传文件 
  23.  * @author linwei 
  24.  * 
  25.  */  
  26. public class MultipartEntityUtil {  
  27.   
  28.     public static String postFile(File file,String url) throws ClientProtocolException, IOException {  
  29.   
  30.         FileBody bin = null;  
  31.         HttpClient httpclient = new DefaultHttpClient();  
  32. //      httpclient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");  
  33.         HttpPost httppost = new HttpPost(url);  
  34.         if(file != null) {  
  35.             bin = new FileBody(file);  
  36.         }  
  37.   
  38.         StringBody businessType = new StringBody("photo");  
  39.         System.out.println(Charset.defaultCharset());  
  40.         StringBody password = new StringBody("测试上大多数123。",Charset.forName("UTF-8"));  
  41.           
  42.         MultipartEntity reqEntity = new MultipartEntity();  
  43.         reqEntity.addPart("businessType", businessType);  
  44.         reqEntity.addPart("password", password);  
  45.         reqEntity.addPart("data", bin);  
  46.         httppost.setEntity(reqEntity);  
  47.         System.out.println("执行: " + httppost.getRequestLine());  
  48.           
  49.         HttpResponse response = httpclient.execute(httppost);  
  50.         System.out.println("statusCode is " + response.getStatusLine().getStatusCode());  
  51.         HttpEntity resEntity = response.getEntity();  
  52.         System.out.println("----------------------------------------");  
  53.         System.out.println(response.getStatusLine());  
  54.         if (resEntity != null) {  
  55.           System.out.println("返回长度: " + resEntity.getContentLength());  
  56.           System.out.println("返回类型: " + resEntity.getContentType());  
  57.           InputStream in = resEntity.getContent();  
  58.           System.out.println("in is " + in);  
  59.           System.out.println(IoStreamUtil.getStringFromInputStream(in));  
  60.         }  
  61.         if (resEntity != null) {  
  62.           resEntity.consumeContent();  
  63.         }  
  64.         return null;  
  65.     }  
  66.       
  67.     public static void main(String[] args) throws ClientProtocolException, IOException {  
  68.       
  69.         File file = new File("d:/test.jpg");  
  70.         String url = "http://localhost:8081/uploadFile.action";  
  71.         postFile(file,url);   
  72.     }  
  73.       
  74. }  


抱歉!评论已关闭.