<rt id="bn8ez"></rt>
<label id="bn8ez"></label>

  • <span id="bn8ez"></span>

    <label id="bn8ez"><meter id="bn8ez"></meter></label>

    Natural

     

    servlet偽異步上傳文件

    在web開發中,上傳文件是常遇到的問題。
    本文在頁面上用iframe來“異步”上傳,并返回上傳結果;來實現常見的文件異步上傳。

    常用的手法,通過一個隱藏的iframe來“異步”
    <form action="servletUploadFile" target="_fileUpload" method="post" enctype="multipart/form-data" name="form1">   
        
    <input type="file" name="file" class="text"/>   
        
    <input type="submit" name="submit" value="上傳"/>   
    </form>
        
    <div id="_uploadresult">這里用來顯示上傳結果</div>
        
    <iframe name="_fileUpload" style="display:none"></iframe>

    通過 commons-fileupload.jar包實現上傳功能的servlet

      1 package com.company.servlet;
      2 
      3 import java.io.File;
      4 import java.io.IOException;
      5 import java.io.PrintWriter;
      6 import java.util.Iterator;
      7 import java.util.List;
      8 
      9 import javax.servlet.ServletConfig;
     10 import javax.servlet.ServletContext;
     11 import javax.servlet.ServletException;
     12 import javax.servlet.http.HttpServlet;
     13 import javax.servlet.http.HttpServletRequest;
     14 import javax.servlet.http.HttpServletResponse;
     15 
     16 import org.apache.commons.fileupload.DiskFileUpload;
     17 import org.apache.commons.fileupload.FileItem;
     18 import org.apache.commons.fileupload.FileUploadException;
     19 import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
     20 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
     21 import org.apache.commons.fileupload.servlet.ServletFileUpload;
     22 
     23 public class UploadFile extends HttpServlet {
     24 
     25     private String uploadPath; // 上傳文件的目錄  
     26     private String uploadtempPath; // 臨時文件目錄  
     27     
     28     private static final long serialVersionUID = 1068590804829697704L;  
     29     private ServletContext sc;//獲取設備上下文對象  
     30     private String savePath;//保存的路徑web.xml中所配置的路徑
     31     private String savePathTemp;//上傳時臨時保存的路徑 web.xml中所配置的路徑
     32     
     33     /*
     34     public void doPost(HttpServletRequest request, HttpServletResponse response)
     35     throws ServletException, IOException 
     36     {
     37         response.setContentType("text/html;charset=utf-8");
     38         final long MAX_SIZE = 1024 * 1024 * 1024;// 設置上傳文件最大為 1G
     39         final String str_MAX_SIZE = "1G"; //用于輸出
     40 
     41         final String[] allowedExt = new String[] { "flv" }; // 允許上傳的文件格式的列表  
     42 
     43         StringBuffer result = null;    // 準備寫到頁面的結果信息
     44         List fileItems = null;
     45         PrintWriter out = response.getWriter();
     46 
     47 
     48         // 實例化一個硬盤文件工廠,用來配置上傳組件ServletFileUpload  
     49         DiskFileItemFactory dfif = new DiskFileItemFactory(); 
     50 
     51         dfif.setSizeThreshold(4096);// 設置上傳文件時用于臨時存放文件的內存大小,這里是4K.多于的部分將臨時存在硬盤  
     52         dfif.setRepository(new File(uploadtempPath));// 設置存放臨時文件的目錄,保存在web根目錄下的web.xml配置文件中savePathTemp目錄下 
     53 
     54         // 用以上工廠實例化上傳組件  
     55         ServletFileUpload sfu = new ServletFileUpload(dfif);
     56 
     57 
     58         sfu.setSizeMax(MAX_SIZE);   // 設置最大文件尺寸
     59 
     60         try
     61         {  
     62             fileItems = sfu.parseRequest(request);  // 得到所有的文件:
     63         } catch (FileUploadException e) // 處理文件尺寸過大異常  
     64         {
     65             if (e instanceof SizeLimitExceededException) 
     66             {  
     67                 result = new StringBuffer("文件尺寸超過規定大小:" + str_MAX_SIZE );
     68                 myPrintOut(out,result.toString()); 
     69                 return;  
     70             }  
     71             e.printStackTrace();  
     72         }  
     73 
     74         // 沒有文件上傳  
     75         if (fileItems == null || fileItems.size() == 0) {  
     76             result = new StringBuffer("請選擇上傳文件");
     77             myPrintOut(out,result.toString());  
     78             return;  
     79         }
     80 
     81         Iterator iter = fileItems.iterator();   
     82         
     83         // 依次處理每一個文件:   
     84         while(iter.hasNext()) 
     85         {
     86             FileItem fileItem = null;
     87             String path = null;
     88             long size = 0; 
     89             
     90             fileItem = (FileItem)iter.next();   
     91          
     92             if(fileItem == null || fileItem.isFormField())// 當前是一個表單項
     93                 continue;
     94     
     95             path = fileItem.getName();   // 獲得文件名 或得到文件的完整路徑 
     96          
     97             size = fileItem.getSize();  // 得到文件的大小
     98     
     99             if ("".equals(path) || size == 0) {  
    100                 result = new StringBuffer("請選擇上傳文件");
    101                 myPrintOut(out,result.toString()); 
    102                 return;  
    103             }  
    104 
    105             // 得到去除路徑的文件名  
    106             String t_name = path.substring(path.lastIndexOf("\\") + 1);  
    107             // 得到文件的擴展名(無擴展名時將得到全名)  
    108             String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);  
    109          
    110             // 拒絕接受規定文件格式之外的文件類型  
    111             int allowFlag = 0;  
    112             int allowedExtCount = allowedExt.length;  
    113             for (; allowFlag < allowedExtCount; allowFlag++) 
    114             {  
    115                 if (allowedExt[allowFlag].equals(t_ext))  
    116                     break;  
    117             }  
    118             if (allowFlag == allowedExtCount) 
    119             {
    120                 result = new StringBuffer("請上傳以下類型的文件&nbsp;&nbsp;");
    121                 
    122                 for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)  
    123                     result.append(allowedExt[allowFlag]+"&nbsp;");
    124                 
    125                 myPrintOut(out,result.toString());
    126                 return;  
    127             }  
    128     
    129             long now = System.currentTimeMillis();  // 根據系統時間生成上傳后保存的文件名
    130     
    131             String prefix = String.valueOf(now);  
    132             // 保存的最終文件完整路徑,保存在web根目錄下的web.xml配置文件中savePath目錄下  
    133             String u_name = uploadPath  +"\\" + prefix + "." + t_ext;  
    134     
    135             // 寫入文件   
    136             try {
    137                 fileItem.write(new File(u_name));
    138             } catch (Exception e) 
    139             {
    140                 e.printStackTrace();
    141             }
    142     
    143             result = new StringBuffer("文件上傳成功. 已保存為:");
    144             result.append(u_name);
    145 
    146             myPrintOut(out,result.toString());
    147         }
    148     }
    149     */
    150     
    151     public void doPost(HttpServletRequest request, HttpServletResponse response)
    152             throws ServletException, IOException 
    153     {
    154         response.setContentType("text/html;charset=utf-8");
    155         final long MAX_SIZE = 1024 * 1024 * 1024;// 設置上傳文件最大為 1G
    156         final String str_MAX_SIZE = "1G"//用于輸出
    157         
    158         final String[] allowedExt = new String[] { "flv" }; // 允許上傳的文件格式的列表  
    159         
    160         StringBuffer result = null;    // 準備寫到頁面的結果信息
    161         List fileItems = null;
    162         PrintWriter out = response.getWriter();
    163         
    164         DiskFileUpload fu = new DiskFileUpload();   
    165         
    166         fu.setSizeMax(MAX_SIZE);   // 設置最大文件尺寸
    167         fu.setSizeThreshold(4096); // 設置緩沖區大小,這里是4kb
    168         fu.setRepositoryPath(uploadtempPath);   // 設置臨時目錄:
    169         
    170         try
    171         {  
    172             fileItems = fu.parseRequest(request);  // 得到所有的文件:
    173         } catch (FileUploadException e) // 處理文件尺寸過大異常  
    174         {
    175             if (e instanceof SizeLimitExceededException) 
    176             {  
    177                 result = new StringBuffer("文件尺寸超過規定大小:" + str_MAX_SIZE );
    178                 myPrintOut(out,result.toString()); 
    179                 return;  
    180             }  
    181             e.printStackTrace();  
    182         }  
    183         
    184         // 沒有文件上傳  
    185         if (fileItems == null || fileItems.size() == 0) {  
    186                 result = new StringBuffer("請選擇上傳文件");
    187                 myPrintOut(out,result.toString());  
    188              return;  
    189         }
    190         
    191         Iterator iter = fileItems.iterator();   
    192 
    193         // 依次處理每一個文件:   
    194         while(iter.hasNext()) 
    195         {
    196             FileItem fileItem = null;
    197             String path = null;
    198             long size = 0
    199 
    200             fileItem = (FileItem)iter.next();   
    201                  
    202             if(fileItem == null || fileItem.isFormField())// 當前是一個表單項
    203                 continue;
    204             
    205             path = fileItem.getName();   // 獲得文件名 或得到文件的完整路徑 
    206                  
    207             size = fileItem.getSize();  // 得到文件的大小
    208             
    209             if ("".equals(path) || size == 0) {  
    210                     result = new StringBuffer("請選擇上傳文件");
    211                     myPrintOut(out,result.toString()); 
    212                  return;  
    213             }  
    214        
    215             // 得到去除路徑的文件名  
    216             String t_name = path.substring(path.lastIndexOf("\\"+ 1);  
    217             // 得到文件的擴展名(無擴展名時將得到全名)  
    218             String t_ext = t_name.substring(t_name.lastIndexOf("."+ 1);  
    219                  
    220             // 拒絕接受規定文件格式之外的文件類型  
    221             int allowFlag = 0;  
    222             int allowedExtCount = allowedExt.length;  
    223             for (; allowFlag < allowedExtCount; allowFlag++
    224             {  
    225                 if (allowedExt[allowFlag].equals(t_ext))  
    226                     break;  
    227             }  
    228             if (allowFlag == allowedExtCount) 
    229             {
    230                 result = new StringBuffer("請上傳以下類型的文件&nbsp;&nbsp;");
    231                      
    232                 for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)  
    233                     result.append(allowedExt[allowFlag]+"&nbsp;");
    234                     
    235                     myPrintOut(out,result.toString());
    236                     return;  
    237             }  
    238             
    239             long now = System.currentTimeMillis();  // 根據系統時間生成上傳后保存的文件名
    240             
    241             String prefix = String.valueOf(now);  
    242             // 保存的最終文件完整路徑,保存在web根目錄下的web.xml配置文件中savePath目錄下  
    243             String u_name = uploadPath  +"\\" + prefix + "." + t_ext;  
    244             
    245             // 寫入文件   
    246             try {
    247                 fileItem.write(new File(u_name));
    248             } catch (Exception e) 
    249             {
    250                 e.printStackTrace();
    251             }
    252             
    253             result = new StringBuffer("文件上傳成功. 已保存為:");
    254             result.append(prefix + "." + t_ext);
    255 
    256             myPrintOut(out,result.toString());
    257          }
    258     }
    259     
    260     public void myPrintOut(PrintWriter out, String str)
    261     {
    262         out.println("<script>window.parent.document.getElementById(\"_uploadresult\").innerHTML='"+str+"'</script>");
    263     }
    264 
    265     public void init(ServletConfig config) throws ServletException {
    266         //獲取配置文件保存的變量值  
    267         savePath = config.getInitParameter("savePath");  
    268         savePathTemp  = config.getInitParameter("savePathTemp"); 
    269         //獲取Servlet上下文對象  
    270         sc = config.getServletContext(); 
    271         
    272         uploadPath = sc.getRealPath("/")+savePath;//上傳文件的路徑
    273         uploadtempPath = sc.getRealPath("/")+savePathTemp;//上傳文件臨時文件的路徑
    274         
    275         //      文件夾不存在就自動創建:   
    276         if(!new File(uploadPath).isDirectory())   
    277             new File(uploadPath).mkdirs();   
    278         if(!new File(uploadtempPath).isDirectory())   
    279             new File(uploadtempPath).mkdirs(); 
    280     }
    281 
    282 }
    283 

    在web.xml中配置一下
    其中參數
    savePath是用來設置上傳文件的路徑
    savePathTemp是用來設置上傳文件的臨時路徑(web應用根目錄下)
    <servlet>
        
    <servlet-name>servletUploadFile</servlet-name>
        
    <servlet-class>com.company.servlet.UploadFile</servlet-class>
        
    <init-param>
          
    <param-name>savePath</param-name>
          
    <param-value>fileUpload</param-value>
        
    </init-param>
        
    <init-param>
          
    <param-name>savePathTemp</param-name>
          
    <param-value>fileUploadTemp</param-value>
        
    </init-param>
      
    </servlet>
      
    <servlet-mapping>
        
    <servlet-name>servletUploadFile</servlet-name>
        
    <url-pattern>/servletUploadFile</url-pattern>
      
    </servlet-mapping>


    posted on 2010-03-24 22:50 此號已被刪 閱讀(499) 評論(0)  編輯  收藏 所屬分類: J2EE

    導航

    統計

    常用鏈接

    留言簿(8)

    隨筆分類(83)

    隨筆檔案(78)

    文章檔案(2)

    相冊

    收藏夾(7)

    最新隨筆

    搜索

    積分與排名

    最新評論

    閱讀排行榜

    評論排行榜

    主站蜘蛛池模板: 亚洲国产精品嫩草影院在线观看| 亚洲伊人久久大香线蕉在观| 久久久久久久99精品免费| 综合自拍亚洲综合图不卡区| 德国女人一级毛片免费| 国产高清对白在线观看免费91| 亚洲色图综合网站| 波多野结衣中文一区二区免费| 日本视频免费高清一本18| 亚洲精品美女久久久久久久| 国产亚洲高清不卡在线观看| 女人18一级毛片免费观看| 国产午夜无码精品免费看| 亚洲国产成人久久一区二区三区 | 国产亚洲精品无码专区| 鲁大师在线影院免费观看 | 中文无码成人免费视频在线观看| 亚洲综合中文字幕无线码| 中文字幕久久亚洲一区| 拨牐拨牐x8免费| 无码国产精品一区二区免费模式 | 日韩免费高清一级毛片| 亚洲综合激情九月婷婷| 亚洲精品国产自在久久| 青青草免费在线视频| 日本免费一区二区三区四区五六区 | 亚洲视频免费在线看| 亚洲AV无码不卡在线观看下载| 中文字幕看片在线a免费| 亚洲日本VA中文字幕久久道具| 亚洲成AV人片在WWW色猫咪| 亚洲国产91精品无码专区| 无码人妻一区二区三区免费| 久久成人免费播放网站| 免费很黄无遮挡的视频毛片| 国产精品亚洲一区二区麻豆| 亚洲国产精久久久久久久| 国产亚洲自拍一区| 亚洲AV无码乱码在线观看牲色 | 久久亚洲sm情趣捆绑调教 | 日日狠狠久久偷偷色综合免费|