利用commons-fileupload实现多个文件上传

Java代码 复制代码
  1.  1. <html>     
  2.  2. <head>     
  3.  3.     <meta http-equiv="Content-Type" content="text/html; charset=GB18030">     
  4.  4.     <title>File upload</title>     
  5.  5. </head>     
  6.  6. <body>     
  7.  7.     <form name="myform" action="demo2.jsp" method="post"     
  8.  8.        enctype="multipart/form-data">     
  9.  9.        File1:<br>     
  10. 10.        <input type="file" name="myfile"><br>     
  11. 11.        File2:<br>     
  12. 12.        <input type="file" name="myfile"><br>     
  13. 13.        <br>     
  14. 14.        <input type="submit" name="submit" value="Commit">     
  15. 15.     </form>     
  16. 16. </body>     
  17. 17. </html>    
   1. <html>  
   2. <head>  
   3.     <meta http-equiv="Content-Type" content="text/html; charset=GB18030">  
   4.     <title>File upload</title>  
   5. </head>  
   6. <body>  
   7.     <form name="myform" action="demo2.jsp" method="post"  
   8.        enctype="multipart/form-data">  
   9.        File1:<br>  
  10.        <input type="file" name="myfile"><br>  
  11.        File2:<br>  
  12.        <input type="file" name="myfile"><br>  
  13.        <br>  
  14.        <input type="submit" name="submit" value="Commit">  
  15.     </form>  
  16. </body>  
  17. </html>  

  
  
Java代码 复制代码
  1.   1package com.zj.sample;     
  2.   2.       
  3.   3import java.io.File;     
  4.   4import java.io.IOException;     
  5.   5import java.util.Iterator;     
  6.   6import java.util.List;     
  7.   7.       
  8.   8import javax.servlet.ServletException;     
  9.   9import javax.servlet.http.HttpServlet;     
  10.  10import javax.servlet.http.HttpServletRequest;     
  11.  11import javax.servlet.http.HttpServletResponse;     
  12.  12.       
  13.  13import org.apache.commons.fileupload.DiskFileUpload;     
  14.  14import org.apache.commons.fileupload.FileItem;     
  15.  15import org.apache.commons.fileupload.FileUploadException;     
  16.  16import org.apache.commons.fileupload.disk.DiskFileItemFactory;     
  17.  17import org.apache.commons.fileupload.servlet.ServletFileUpload;     
  18.  18.       
  19.  19@SuppressWarnings("serial")     
  20.  20public class Upload extends HttpServlet {     
  21.  21.     private String uploadPath = "D://temp"// 上传文件的目录     
  22.  22.     private String tempPath = "d://temp//buffer//"// 临时文件目录     
  23.  23.     File tempPathFile;     
  24.  24.       
  25.  25.     @SuppressWarnings("unchecked")     
  26.  26.     public void doPost(HttpServletRequest request, HttpServletResponse response)     
  27.  27.            throws IOException, ServletException {     
  28.  28.             
  29.  29.         String msg = "";     
  30.  30.         DiskFileUpload fu = new DiskFileUpload();     
  31.  31.         // 设置允许用户上传文件大小,单位:字节     
  32.  32.         // fu.setSizeMax(10000000);     
  33.  33.         // 设置最多只允许在内存中存储的数据,单位:字节     
  34.  34.         // fu.setSizeThreshold(4096);     
  35.  35.         // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录     
  36.  36.         //(临时存放目录,文件上传完毕后有办法清除它吗?)     
  37.  37.         fu.setRepositoryPath("D://TEMP");     
  38.  38.         //开始读取上传信息     
  39.  39.         List fileItems = null;     
  40.  40.         try {     
  41.  41.             fileItems = fu.parseRequest(request);     
  42.  42.         } catch (FileUploadException e1) {     
  43.  43.             // TODO 自动生成 catch 块     
  44.  44.             e1.printStackTrace();     
  45.  45.         }     
  46.  46.         // 依次处理每个上传的文件     
  47.  47.         Iterator iter = fileItems.iterator();     
  48.  48.         while (iter.hasNext())     
  49.  49.         {     
  50.  50.             FileItem item = (FileItem) iter.next();     
  51.  51.             //忽略其他不是文件域的所有表单信息     
  52.  52.             if (!item.isFormField())     
  53.  53.             {     
  54.  54.                 String name = item.getName();//获取上传的文件名     
  55.  55.                 long size = item.getSize();//获取上传的文件大小(字节为单位)     
  56.  56.                 if ((name == null || name.equals("")) && size == 0)     
  57.  57.                 continue;//跳到while检查条件     
  58.  58.                      
  59.  59.                 System.out.println("<tr>");     
  60.  60.                 System.out.println("<td>" + name + "</td>");     
  61.  61.                 System.out.println("<td>" + size + "</td>");     
  62.  62.                      
  63.  63.                 //以下为文件名处理,将上传的文件保存在项目所在目录下。     
  64.  64.                 //获取文件名字符串的长度     
  65.  65.                 int end = name.length();     
  66.  66.                 //返回在此字符串中最右边出现的指定子字符串的索引。     
  67.  67.                 int begin = name.lastIndexOf("//");     
  68.  68.                 File savedFile = new File("c://TEMP", name.substring(     
  69.  69.                 begin + 1, end));     
  70.  70.                 try {     
  71.  71.                     item.write(savedFile);     
  72.  72.                 } catch (Exception e) {     
  73.  73.                     // TODO 自动生成 catch 块     
  74.  74.                     e.printStackTrace();     
  75.  75.                 }     
  76.  76.             }     
  77.  77.         }     
  78.  78.              
  79.  79.              
  80.  80.         try {     
  81.  81.            // Create a factory for disk-based file items     
  82.  82.            DiskFileItemFactory factory = new DiskFileItemFactory();     
  83.  83.       
  84.  84.            // Set factory constraints     
  85.  85.            factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb     
  86.  86.            factory.setRepository(tempPathFile);// 设置缓冲区目录     
  87.  87.       
  88.  88.            // Create a new file upload handler     
  89.  89.            ServletFileUpload upload = new ServletFileUpload(factory);     
  90.  90.       
  91.  91.            // Set overall request size constraint     
  92.  92.            upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB     
  93.  93.       
  94.  94.            List<FileItem> items = upload.parseRequest(request);// 得到所有的文件     
  95.  95.            Iterator<FileItem> i = items.iterator();     
  96.  96.            while (i.hasNext()) {     
  97.  97.               FileItem fi = (FileItem) i.next();     
  98.  98.               String fileName = fi.getName();     
  99.  99.               if (fileName != null) {     
  100. 100.                   File fullFile = new File(fi.getName());     
  101. 101.                   File savedFile = new File(uploadPath, fullFile.getName());     
  102. 102.                   fi.write(savedFile);     
  103. 103.               }     
  104. 104.            }     
  105. 105.            System.out.print("upload succeed");     
  106. 106.        } catch (Exception e) {     
  107. 107.            // 可以跳转出错页面     
  108. 108.            e.printStackTrace();     
  109. 109.        }     
  110. 110.     }     
  111. 111.       
  112. 112.     public void init() throws ServletException {     
  113. 113.        File uploadFile = new File(uploadPath);     
  114. 114.        if (!uploadFile.exists()) {     
  115. 115.            uploadFile.mkdirs();     
  116. 116.        }     
  117. 117.        File tempPathFile = new File(tempPath);     
  118. 118.         if (!tempPathFile.exists()) {     
  119. 119.            tempPathFile.mkdirs();     
  120. 120.        }     
  121. 121.     }     
  122. 122. }     
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值