common-fileupload文件上传及下载

来源:互联网 发布:安卓内核源码查看 编辑:程序博客网 时间:2024/05/26 05:50
 使用common-fileupload组建实现文件上传下载功能, 封装了一个WebFileService的类
Java代码  
[java] view plaincopyprint?
  1. import java.io.BufferedInputStream;     
  2. import java.io.BufferedOutputStream;     
  3. import java.io.File;     
  4. import java.io.FileInputStream;     
  5. import java.io.PrintWriter;     
  6. import java.net.URLEncoder;     
  7. import java.util.ArrayList;     
  8. import java.util.HashMap;     
  9. import java.util.Iterator;     
  10. import java.util.List;     
  11. import java.util.Map;     
  12.    
  13. import javax.servlet.http.HttpServletRequest;     
  14. import javax.servlet.http.HttpServletResponse;     
  15.     
  16. import org.apache.commons.fileupload.FileItem;     
  17. import org.apache.commons.fileupload.FileUploadException;     
  18. import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;     
  19. import org.apache.commons.fileupload.disk.DiskFileItemFactory;     
  20. import org.apache.commons.fileupload.servlet.ServletFileUpload;     
  21.    
  22. /**   
  23.  * <p>Title: 处理文件上传下载的类</p>   
  24.  * <p>Description:    
  25.  *    通过设置long MAX_SIZE可以设置上传文件的大小限制   
  26.  *    通过设置String[] allowedExt设置允许上传的文件类型   
  27.  *    通过Map parameters获得表单域的信息   
  28.  *    通过List fileInfoList获取上传的每个文件的详细信息   
  29.  * </p>   
  30.  * <p>Copyright: Copyright (c) 2006, 2008 Royzhou Corporation.All rights reserved. </p>   
  31.  * @author royzhou   
  32.  * 2009-02-20   
  33.  */    
  34. public class FileWebService {     
  35.     /**   
  36.      * 表单域的信息   
  37.      */    
  38.     private Map parameters = null;     
  39.          
  40.     /**   
  41.      * 文件域的详细信息   
  42.      */    
  43.     private List fileInfoList = null;     
  44.          
  45.     /**   
  46.      * 允许上传的文件大小   
  47.      */    
  48.     private long MAX_SIZE = 10*1024*1024;     
  49.          
  50.     /**   
  51.      * 允许上传的文件类型   
  52.      */    
  53.     private String[] allowedExt = new String[] { "jpg""jpeg""gif""txt","doc""docx""mp3""wma""m4a" };     
  54.          
  55.     public FileWebService() {     
  56.         parameters = new HashMap();     
  57.         fileInfoList = new ArrayList();     
  58.     }     
  59.          
  60.     /**   
  61.      * @param request   
  62.      * @param response   
  63.      * @param path 用户设置的保存路径   
  64.      * 上传文件并获取表单域及文件域的详细信息   
  65.      * @throws Exception   
  66.      */    
  67.     public void upload(HttpServletRequest request, HttpServletResponse response, String path) throws Exception {     
  68.         /**   
  69.          * 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload   
  70.          */    
  71.         DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();     
  72.         diskFileItemFactory.setSizeThreshold(4096);// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘     
  73.         /**   
  74.          * 采用系统临时文件目录作为上传的临时目录   
  75.          */    
  76.         File tempfile = new File(System.getProperty("java.io.tmpdir"));       
  77.         diskFileItemFactory.setRepository(tempfile);     
  78.              
  79.         /**   
  80.          * 用以上工厂实例化上传组件   
  81.          * 设置最大上传尺寸   
  82.          */    
  83.         ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);     
  84.         fileUpload.setSizeMax(MAX_SIZE);     
  85.              
  86.         /**   
  87.          * 调用FileUpload.settingHeaderEncoding(”UTF-8″),这项设置可以解决路径或者文件名为乱码的问题。   
  88.          * 设置输出字符集   
  89.          */    
  90.         fileUpload.setHeaderEncoding("UTF-8");     
  91.         response.setContentType("text/html;charset=utf-8");     
  92.              
  93.         PrintWriter out = response.getWriter();     
  94.         /**   
  95.          * 从request得到 所有 上传域的列表   
  96.          */    
  97.         List fileList = null;     
  98.         try {     
  99.             fileList = fileUpload.parseRequest(request);     
  100.         } catch (FileUploadException e) {     
  101.             if (e instanceof SizeLimitExceededException) {     
  102.                 /**   
  103.                  * 文件大小超出限制   
  104.                  */    
  105.                 out.println("文件尺寸超过规定大小:" + MAX_SIZE + "字节<p />");     
  106.                 out.println("<a href=\"upload.html\" target=\"_top\">返回</a>");     
  107.                 return;     
  108.             }     
  109.             e.printStackTrace();     
  110.         }     
  111.         /**   
  112.          * 没有上传文件   
  113.          */    
  114.         if (fileList == null || fileList.size() == 0) {     
  115.             out.println("请选择上传文件<p />");     
  116.             out.println("<a href=\"upload.html\" target=\"_top\">返回</a>");     
  117.             return;     
  118.         }     
  119.         /**   
  120.          * 得到所有上传的文件   
  121.          * 对文件域操作   
  122.          * 并保存每个文件的详细信息   
  123.          */    
  124.         Iterator fileItr = fileList.iterator();     
  125.         Map fileInfo = null;     
  126.         while (fileItr.hasNext()) {     
  127.             FileItem fileItem = null;     
  128.             long size = 0;     
  129.             String userPath = null;     
  130.             String serverPath = null;     
  131.             String fileName = null;     
  132.             String fileExt = null;     
  133.             fileItem = (FileItem) fileItr.next();     
  134.             /**   
  135.              * 忽略简单form字段而不是上传域的文件域(<input type="text" />等)   
  136.              */    
  137.             if (!fileItem.isFormField()) {     
  138.                  
  139.                 /**   
  140.                  * 得到文件的详细信息   
  141.                  * 客户端完整路径:userPath   
  142.                  * 服务器端完整路径:serverPath   
  143.                  * 大小:size   
  144.                  * 文件名:fileName   
  145.                  * 扩展名:fileExt   
  146.                  *    
  147.                  */    
  148.                 userPath = fileItem.getName();     
  149.                 size = fileItem.getSize();     
  150.                 if ("".equals(userPath) || size == 0) {     
  151.                     out.println("请选择上传文件<p />");     
  152.                     out.println("<a href=\"upload.html\" target=\"_top\">返回</a>");     
  153.                     return;     
  154.                 }     
  155.                 fileName = userPath.substring(userPath.lastIndexOf("\\") + 1);     
  156.                 fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);     
  157.     
  158.                 /**   
  159.                  * 文件类型是否合法   
  160.                  */    
  161.                 int allowFlag = 0;     
  162.                 int allowedExtCount = allowedExt.length;     
  163.                 for (; allowFlag < allowedExtCount; allowFlag++) {     
  164.                     if (allowedExt[allowFlag].toLowerCase().equals(fileExt.toLowerCase()))     
  165.                         break;     
  166.                 }     
  167.                 if (allowFlag == allowedExtCount) {     
  168.                     out.println("请上传以下类型的文件<p />");     
  169.                     for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)     
  170.                         out.println("*." + allowedExt[allowFlag].toLowerCase()     
  171.                                 + "   ");     
  172.                     out     
  173.                             .println("<p /><a href=\"upload.html\" target=\"_top\">返回</a>");     
  174.                     return;     
  175.                 }     
  176.                 /**   
  177.                  * 根据系统时间生成上传后保存的文件名   
  178.                  */    
  179.                 serverPath = path + System.currentTimeMillis() + "." + fileExt;     
  180.                      
  181.                 try {     
  182.                     /**   
  183.                      * 保存文件   
  184.                      */    
  185.                     File diskPath = new File(path);     
  186.                     if(!diskPath.exists()) {     
  187.                         diskPath.mkdirs();     
  188.                     }     
  189.                     File diskFile = new File(serverPath);     
  190.                     if(!diskFile.exists()) {     
  191.                         diskFile.createNewFile();     
  192.                     }     
  193.                     fileItem.write(diskFile);     
  194.                     out.println("文件上传成功. 已保存为: " + serverPath     
  195.                             + "   文件大小: " + size + "字节<p />");     
  196.                     out.println("<form action=\"FileDownloadServlet\" method=\"post\">");     
  197.                     out.println("  <input type=\"hidden\" name=\"fileName\" value=\"" + fileName + "\" />");     
  198.                     out.println("  <input type=\"hidden\" size=\"200\" name=\"filePath\" value=\"" + serverPath + "\" />");     
  199.                     out.println("  <input type=\"submit\" name=\"submit\" value=\"下载上传的文件\" />");     
  200.                     out.println("</form>");     
  201.                 } catch (Exception e) {     
  202.                     e.printStackTrace();     
  203.                 }     
  204.                      
  205.                 fileInfo = new HashMap();     
  206.                 fileInfo.put("size", String.valueOf(size));     
  207.                 fileInfo.put("userpath", userPath);     
  208.                 fileInfo.put("name",fileName);     
  209.                 fileInfo.put("ext", fileExt);     
  210.                 fileInfo.put("serverpath", serverPath);     
  211.                 fileInfoList.add(fileInfo);     
  212.             } else {     
  213.                 String fieldName = fileItem.getFieldName();     
  214.                 /**   
  215.                  * 在取字段值的时候,用FileItem.getString(”UTF-8″),这项设置可以解决获取的表单字段为乱码的问题。   
  216.                  */      
  217.                 String value = fileItem.getString("UTF-8");     
  218.                 parameters.put(fieldName, value);     
  219.             }     
  220.         }     
  221.     }     
  222.          
  223.          
  224.     /**   
  225.      * 该方法支持支持国际化   
  226.      * 但是文件名不能超过17个汉字   
  227.      * 而且在IE6下存在bug   
  228.      */    
  229.     public void downloadI18N(HttpServletRequest request, HttpServletResponse response) throws Exception {     
  230.         response.setContentType("text/html;charset=utf-8");     
  231.         java.io.BufferedInputStream bis = null;     
  232.         java.io.BufferedOutputStream bos = null;     
  233.     
  234.         String filePath = request.getParameter("filePath");     
  235.         String fileName = request.getParameter("fileName");     
  236.         System.out.println(fileName);     
  237.         try {     
  238.             long fileLength = new File(filePath).length();     
  239.     
  240.             fileName = URLEncoder.encode(fileName, "UTF-8");     
  241.             response.setContentType("application/x-msdownload;");     
  242.             response.setHeader("Content-disposition""attachment; filename=" + fileName);     
  243.             response.setHeader("Content-Length", String.valueOf(fileLength));     
  244.     
  245.             bis = new BufferedInputStream(new FileInputStream(filePath));     
  246.             bos = new BufferedOutputStream(response.getOutputStream());     
  247.             byte[] buff = new byte[2048];     
  248.             int bytesRead;     
  249.             while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {     
  250.                 bos.write(buff, 0, bytesRead);     
  251.             }     
  252.         } catch (Exception e) {     
  253.             e.printStackTrace();     
  254.         } finally {     
  255.             if (bis != null)     
  256.                 bis.close();     
  257.             if (bos != null)     
  258.                 bos.close();     
  259.         }     
  260.     }     
  261.     
  262.     /**   
  263.      * 支持中文,文件名长度无限制   
  264.      * 不支持国际化   
  265.      */    
  266.     public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {     
  267.         response.setContentType("text/html;charset=utf-8");     
  268.         request.setCharacterEncoding("UTF-8");     
  269.         java.io.BufferedInputStream bis = null;     
  270.         java.io.BufferedOutputStream bos = null;     
  271.     
  272.         String filePath = request.getParameter("filePath");     
  273.         String fileName = request.getParameter("fileName");     
  274.         System.out.println(fileName);     
  275.         try {     
  276.             long fileLength = new File(filePath).length();     
  277.     
  278.             response.setContentType("application/x-msdownload;");     
  279.             response.setHeader("Content-disposition""attachment; filename=" + new String(fileName.getBytes("GBK"),"ISO8859-1"));     
  280.             response.setHeader("Content-Length", String.valueOf(fileLength));     
  281.     
  282.             bis = new BufferedInputStream(new FileInputStream(filePath));     
  283.             bos = new BufferedOutputStream(response.getOutputStream());     
  284.             byte[] buff = new byte[2048];     
  285.             int bytesRead;     
  286.             while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {     
  287.                 bos.write(buff, 0, bytesRead);     
  288.             }     
  289.         } catch (Exception e) {     
  290.             e.printStackTrace();     
  291.         } finally {     
  292.             if (bis != null)     
  293.                 bis.close();     
  294.             if (bos != null)     
  295.                 bos.close();     
  296.         }     
  297.     }     
  298.     
  299.     public List getFileInfoList() {     
  300.         return fileInfoList;     
  301.     }     
  302.     
  303.     public void setFileInfoList(List fileInfoList) {     
  304.         this.fileInfoList = fileInfoList;     
  305.     }     
  306.     
  307.     public Map getParameters() {     
  308.         return parameters;     
  309.     }     
  310.     
  311.     public void setParameters(Map parameters) {     
  312.         this.parameters = parameters;     
  313.     }     
  314.     
  315.     public String[] getAllowedExt() {     
  316.         return allowedExt;     
  317.     }     
  318.     
  319.     public void setAllowedExt(String[] allowedExt) {     
  320.         this.allowedExt = allowedExt;     
  321.     }     
  322.     
  323.     public long getMAX_SIZE() {     
  324.         return MAX_SIZE;     
  325.     }     
  326.     
  327.     public void setMAX_SIZE(long max_size) {     
  328.         MAX_SIZE = max_size;     
  329.     }     
  330. }    

实例化之前可以先对上传的文件设置一些参数,如上传文件的大小以及上传文件的类型等等
上传之后的文件信息可以通过fileInfoList遍历获取,表单域信息可以通过parameter获取
原创粉丝点击