上传文件

 
  1. import  java.io.File;  
  2. import  java.io.IOException;  
  3. import  java.io.PrintWriter;  
  4. import  java.util.Iterator;  
  5. import  java.util.List;  
  6.   
  7. import  javax.servlet.ServletException;  
  8. import  javax.servlet.http.HttpServlet;  
  9. import  javax.servlet.http.HttpServletRequest;  
  10. import  javax.servlet.http.HttpServletResponse;  
  11.   
  12. import  org.apache.commons.fileupload.FileItem;  
  13. import  org.apache.commons.fileupload.FileUploadException;  
  14. import  org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;  
  15. import  org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  16. import  org.apache.commons.fileupload.servlet.ServletFileUpload;  
  17.   
  18.   
  19. public   class  FileUploadServlet  extends  HttpServlet {  
  20.     private   static   final   long  serialVersionUID = 1L;  
  21.   
  22.     public  FileUploadServlet() {  
  23.         super ();  
  24.     }  
  25.     protected   void  doGet(HttpServletRequest request,  
  26.             HttpServletResponse response) throws  ServletException, IOException {  
  27.         this .doPost(request, response);  
  28.     }  
  29.   
  30.     protected   void  doPost(HttpServletRequest request,  
  31.             HttpServletResponse response) throws  ServletException, IOException {  
  32.           
  33.         final   long  MAX_SIZE =  300  *  1024  *  1024 ; // 设置上传文件最大值   
  34.         // 允许上传的文件格式的列表   
  35.         final  String[] allowedExt =  new  String[] { "jpg""jpeg""gif""txt" ,  
  36.                 "doc" , "mp3""wma""m4a" , "rar" , "zip"  };  
  37.         response.setContentType("text/html" );  
  38.         // 设置字符编码为UTF-8, 统一编码,处理出现乱码问题   
  39.         response.setCharacterEncoding("UTF-8" );  
  40.   
  41.         // 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload   
  42.         DiskFileItemFactory dfif = new  DiskFileItemFactory();  
  43.         dfif.setSizeThreshold(4096 ); // 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘   
  44.         dfif.setRepository(new  File(request.getRealPath( "/" )  
  45.                 + "ImagesUploadTemp" )); // 设置存放临时文件的目录,web根目录下的ImagesUploadTemp目录   
  46.   
  47.         // 用以上工厂实例化上传组件   
  48.         ServletFileUpload sfu = new  ServletFileUpload(dfif);  
  49.         // 设置最大上传大小   
  50.         sfu.setSizeMax(MAX_SIZE);  
  51.   
  52.         PrintWriter out = response.getWriter();  
  53.         // 从request得到所有上传域的列表   
  54.         List fileList = null ;  
  55.         try  {  
  56.             fileList = sfu.parseRequest(request);  
  57.         } catch  (FileUploadException e) { // 处理文件尺寸过大异常   
  58.             if  (e  instanceof  SizeLimitExceededException) {  
  59.                 out.println("文件尺寸超过规定大小:"  + MAX_SIZE +  "字节<p />" );  
  60.                 out  
  61.                         .println("<a href=/"FileUpload.html/" target=/"_top/">返回</a>" );  
  62.                 return ;  
  63.             }  
  64.             e.printStackTrace();  
  65.         }  
  66.         // 没有文件上传   
  67.         if  (fileList ==  null  || fileList.size() ==  0 ) {  
  68.             out.println("请选择上传文件<p />" );  
  69.             out.println("<a href=/"FileUpload.html/" target=/"_top/">返回</a>" );  
  70.             return ;  
  71.         }  
  72.         // 得到所有上传的文件   
  73.         Iterator fileItr = fileList.iterator();  
  74.         // 循环处理所有文件   
  75.         while  (fileItr.hasNext()) {  
  76.             FileItem fileItem = null ;  
  77.             String path = null ;  
  78.             long  size =  0 ;  
  79.             // 得到当前文件   
  80.             fileItem = (FileItem) fileItr.next();  
  81.             // 忽略简单form字段而不是上传域的文件域(<input type="text" />等)   
  82.             if  (fileItem ==  null  || fileItem.isFormField()) {  
  83.                 continue ;  
  84.             }  
  85.             // 得到文件的完整路径   
  86.             path = fileItem.getName();  
  87.             // 得到文件的大小   
  88.             size = fileItem.getSize();  
  89.             if  ( "" .equals(path) || size ==  0 ) {  
  90.                 out.println("请选择上传文件<p />" );  
  91.                 out  
  92.                         .println("<a href=/"FileUpload.html/" target=/"_top/">返回</a>" );  
  93.                 return ;  
  94.             }  
  95.   
  96.             // 得到去除路径的文件名   
  97.             String t_name = path.substring(path.lastIndexOf("//" ) +  1 );  
  98.             // 得到文件的扩展名(无扩展名时将得到全名)   
  99.             String t_ext = t_name.substring(t_name.lastIndexOf("." ) +  1 );  
  100.             // 拒绝接受规定文件格式之外的文件类型   
  101.             int  allowFlag =  0 ;  
  102.             int  allowedExtCount = allowedExt.length;  
  103.             for  (; allowFlag < allowedExtCount; allowFlag++) {  
  104.                 if  (allowedExt[allowFlag].equals(t_ext))  
  105.                     break ;  
  106.             }  
  107.             if  (allowFlag == allowedExtCount) {  
  108.                 out.println("请上传以下类型的文件<p />" );  
  109.                 for  (allowFlag =  0 ; allowFlag < allowedExtCount; allowFlag++)  
  110.                     out.println("*."  + allowedExt[allowFlag]  
  111.                             + "   " );  
  112.                 out  
  113.                         .println("<p /><a href=/"FileUpload.html/" target=/"_top/">返回</a>" );  
  114.                 return ;  
  115.             }  
  116.   
  117.             long  now = System.currentTimeMillis();  
  118.             // 根据系统时间生成上传后保存的文件名   
  119.             String prefix = String.valueOf(now);  
  120.             // 保存的最终文件完整路径,保存在web根目录下的ImagesUploaded目录下   
  121. //          String u_name = request.getRealPath("/") + "ImagesUploaded/"   
  122. //                  + prefix + "." + t_ext;   
  123.             String filename = prefix + "."  + t_ext;  
  124.             try  {  
  125.                 // 保存文件到C://upload目录下   
  126.                 fileItem.write(new  File( "C://upload//" +filename));  
  127.                 System.out.println(filename);  
  128.                 out.println("文件上传成功. 已保存为: "  + prefix +  "."  + t_ext  
  129.                         + "   文件大小: "  + size +  "字节<p />" );  
  130.                 out  
  131.                         .println("<a href=/"FileUpload.html/" target=/"_top/">继续上传</a>" );  
  132.             } catch  (Exception e) {  
  133.                 e.printStackTrace();  
  134.             }  
  135.         }  
  136.     }  

 

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd" >   
  2. < html >   
  3. < head >   
  4. < meta   http-equiv = "Content-Type"   content = "text/html; charset=UTF-8" >   
  5. < title > 文件上传 </ title >   
  6. </ head >   
  7. < body >   
  8. < form   action = "FileUploadServlet"   method = "post"   
  9.     enctype = "multipart/form-data" >   
  10.     < input   type = "file"   size = "30"   
  11.     name = "file01"   />   < br   />   
  12.         < input   type = "file"   size = "30"   
  13.     name = "file02"   />   < br   />   
  14. < input   name = "up"   type = "submit"   value = "上传"   /> </ form >   
  15. </ body >   
  16. </ html >  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值