春風(fēng)博客

          春天里,百花香...

          導(dǎo)航

          <2008年4月>
          303112345
          6789101112
          13141516171819
          20212223242526
          27282930123
          45678910

          統(tǒng)計(jì)

          公告

          MAIL: junglesong@gmail.com
          MSN: junglesong_5@hotmail.com

          Locations of visitors to this page

          常用鏈接

          留言簿(11)

          隨筆分類(224)

          隨筆檔案(126)

          個(gè)人軟件下載

          我的其它博客

          我的鄰居們

          最新隨筆

          搜索

          積分與排名

          最新評(píng)論

          閱讀排行榜

          評(píng)論排行榜

          使用commons-fileupload實(shí)現(xiàn)單個(gè)和多個(gè)文件上傳

          對(duì)于實(shí)現(xiàn)文件上傳功能來說,Commons-fileupload組件是一個(gè)不錯(cuò)的選擇,本文使用它實(shí)現(xiàn)了單個(gè)文件及多個(gè)文件上傳,這里將實(shí)現(xiàn)過程寫出來與大家共享。

          1.單個(gè)文件上傳。
          頁面代碼:
                 
          ....
          <div id="content">
                      
          <fieldset><legend>下載列表</legend>
                          
          <ul>
                          
          <%
                              List
          <String> downloadList=(List<String>)request.getAttribute("downloadList");    
                              
                              
          if(downloadList!=null){
                                  
          for(String str:downloadList){    
                                      out.print(
          "<li><a href='DownloadFile?file="+str+"'>"+str+"</a></li>");
                                  }
                              }
                          
          %>
                          
          </ul>
                      
          </fieldset>
                  
                      
          <!-- enctype屬性為表單定義了MIME編碼方式,上傳文件的表單enctype屬性必須如此設(shè)置 -->
                      
          <form method="post" action="UploadFile" enctype="multipart/form-data" >
                      
          <p><input type="text" name="fileIntro" value="" />文件介紹</p>
                      
          <p><input type="file" name="myfile1" value="瀏覽文件" /></p>
                      
          <p><input type="submit" value="上傳"/></p>
                      
          </form>
                  
          </div>....
          在上傳表單中,既有普通文本域也有文件上傳域,注意在Servlet中取它們和平常的做法不同:
          Servlet代碼:
          package com.sitinspring.action;

          import java.io.File;
          import java.util.ArrayList;
          import java.util.Iterator;
          import java.util.List;

          import javax.servlet.RequestDispatcher;
          import javax.servlet.ServletException;
          import javax.servlet.http.HttpServlet;
          import javax.servlet.http.HttpServletRequest;
          import javax.servlet.http.HttpServletResponse;

          import org.apache.commons.fileupload.FileItem;
          import org.apache.commons.fileupload.FileItemFactory;
          import org.apache.commons.fileupload.disk.DiskFileItemFactory;
          import org.apache.commons.fileupload.servlet.ServletFileUpload;

          import com.sitinspring.util.UploadUtil;

          /**
           * 用于文件上傳處理的Servlet
           * 
          @author sitinspring
           *
           * @date 2008-2-12
           
          */
          public class UploadFileServlet extends HttpServlet {
              
          private static final long serialVersionUID = 56890894234786L;

              @SuppressWarnings(
          "unchecked")
              
          public void doPost(HttpServletRequest request, HttpServletResponse response)
                      
          throws ServletException, java.io.IOException {
                  request.setCharacterEncoding(
          "UTF-8");

                  
          // 文件上傳部分
                  boolean isMultipart = ServletFileUpload.isMultipartContent(request);
                  
                  
          if (isMultipart == true) {
                      
          try {
                          FileItemFactory factory 
          = new DiskFileItemFactory();
                          ServletFileUpload upload 
          = new ServletFileUpload(factory);
                          
                          
          // 得到所有的表單域,它們目前都被當(dāng)作FileItem
                          List<FileItem> fileItems = upload.parseRequest(request);
                          Iterator
          <FileItem> iter = fileItems.iterator();
                          
                          
          // 依次處理每個(gè)表單域
                          while (iter.hasNext()) {
                              FileItem item 
          = (FileItem) iter.next();
                              
                              
          if(item.isFormField()){
                                  
          // 如果item是正常的表單域
                                  String name = item.getFieldName();
                                  String value 
          = item.getString();
                                  System.out.print(
          "表單域名為:"+name+"表單域值為:"+value);
                              }
                              
          else{
                                  
          // 如果item是文件上傳表單域
                                  
                                  
          // 獲得文件名及路徑
                                  String fileName = item.getName();
                                  
          if (fileName != null) {
                                      File fullFile 
          = new File(item.getName());                            
                                                                  
                                      
          // 如果文件存在則上傳
                                      if(fullFile.exists()){
                                          File fileOnServer 
          = new File(UploadUtil.getUploadPath(),
                                                  fullFile.getName());
                                          item.write(fileOnServer);
                                          
                                          System.out.println(
          "文件"+fileOnServer.getName()+"上傳成功");
                                      }
                                  }
                              }
                          }                
                      } 
          catch (Exception e) {
                          e.printStackTrace();
                      }
                  } 
          else {
                      System.out.println(
          "the enctype must be multipart/form-data");
                  }
                  
                  
          // 取得服務(wù)器中已有文件的下載列表
                  List<String> fileListInServer=new ArrayList<String>(); 
                  
                  File dir 
          = new File(UploadUtil.getUploadPath());        
                  String[] children 
          = dir.list();
                  
          if (children != null) {
                      
          for (int i=0; i<children.length; i++) {
                          fileListInServer.add(children[i]);                
                      }
                  }
                  
                  request.setAttribute(
          "downloadList", fileListInServer);

                  
          // 跳回原頁面
                  RequestDispatcher dispatcher = request
                          .getRequestDispatcher(
          "/web/page/uploadtoserver.jsp");
                  dispatcher.forward(request, response);
                  
          return;
              }

              
          public void doGet(HttpServletRequest request, HttpServletResponse response)
                      
          throws ServletException, java.io.IOException {
                  doPost(request, response);
              }
          }

          從上面的代碼可以看出,無論是否文件上傳表單域都被當(dāng)成了FileItem來處理,要區(qū)別開來使用isFormField()方法即可,返回真是常規(guī)表單域,返回假則是文件上傳表單域。

          2.多個(gè)文件上傳到服務(wù)器端。

          這里采用JS動(dòng)態(tài)生成幾個(gè)文件上傳表單域即可,Servlet無需改變。
          多文件上傳頁面代碼如下:
          <%@ page contentType="text/html; charset=UTF-8"%>
          <%@page language="java" import="java.util.List"%>

          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
          <html>
          <head>
          <title>上傳多個(gè)文件到服務(wù)器</title>
          <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
          <link rel="stylesheet" rev="stylesheet" href="web/css/style.css"
              type
          ="text/css" />
          </head>

          <body>
              
          <div id="bodyDiv">
                  
          <div id="header">
                      
          <jsp:include page="/web/page/branch/header.jsp"/>
                  
          </div>
                  
          <div id="sidebar">
                      
          <jsp:include page="/web/page/branch/sidebar.jsp"/>
                  
          </div>
                  
          <div id="content">
                      
          <fieldset><legend>下載列表</legend>
                          
          <ul>
                          
          <%
                              List
          <String> downloadList=(List<String>)request.getAttribute("downloadList");    
                              
                              
          if(downloadList!=null){
                                  
          for(String str:downloadList){    
                                      out.print(
          "<li><a href='DownloadFile?file="+str+"'>"+str+"</a></li>");
                                  }
                              }
                          
          %>
                          
          </ul>
                      
          </fieldset>
                  
                      
          <!-- enctype屬性為表單定義了MIME編碼方式,上傳文件的表單enctype屬性必須如此設(shè)置 -->
                      
          <form name="uploadForm" method="post" action="UploadFile" enctype="multipart/form-data" >
                      
          <p><input type="button" value="增加上傳按鈕" onclick="addUploadButton()"/></p>
                      
          <p><input type="file" name="myfile1" value="瀏覽文件" /></p>
                      
          <p><input type="submit" value="上傳"/></p>
                      
          </form>
                  
          </div>
                  
          <div id="footer">
                      
          <jsp:include page="/web/page/branch/footer.jsp"/>
                  
          </div>
              
          </div>
          </body>

          JS代碼:
          <script LANGUAGE="JavaScript">
          <!--
          var count=1;

          function addUploadButton(){    
              
          // 按ID找到FOrm
              var uploadForm=document.getElementById("uploadForm");    
              
              
          // 創(chuàng)建P元素
              var pNode=document.createElement("p");
              
              
          // 累加Count以觀察次數(shù)
              count=count+1;
              
              pNode.innerHTML
          ="<input type='file' name='myfile"+count+"' value='瀏覽文件'/>";
              
              
          // 將P元素添加到body中
              uploadForm.appendChild(pNode);
          }

          //-->
          </script>
          </html>


          實(shí)例代碼:
          http://www.aygfsteel.com/Files/sitinspring/FileUpload20080412145412.rar



          posted on 2008-04-12 14:16 sitinspring 閱讀(34052) 評(píng)論(13)  編輯  收藏 所屬分類: Web開發(fā)

          評(píng)論

          # re: 使用commons-fileupload實(shí)現(xiàn)單個(gè)和多個(gè)文件上傳 2008-04-14 17:21 anthony.rao

          會(huì)不會(huì)有中文問題?  回復(fù)  更多評(píng)論   

          # re: 使用commons-fileupload實(shí)現(xiàn)單個(gè)和多個(gè)文件上傳 2008-04-14 17:22 anthony.rao

          就是下載的時(shí)候.用href直接連過去 ,要是文件名稱是中文的話,有問題嗎?  回復(fù)  更多評(píng)論   

          # re: 使用commons-fileupload實(shí)現(xiàn)單個(gè)和多個(gè)文件上傳 2008-04-14 17:40 如坐春風(fēng)

          @anthony.rao

          有中文問題,有待發(fā)掘一下.  回復(fù)  更多評(píng)論   

          # re: 使用commons-fileupload實(shí)現(xiàn)單個(gè)和多個(gè)文件上傳 2008-12-03 13:21 e

          中文問題有沒有一個(gè)很好的解決辦法 希望能指教下  回復(fù)  更多評(píng)論   

          # re: 使用commons-fileupload實(shí)現(xiàn)單個(gè)和多個(gè)文件上傳 2009-03-04 11:45 zth

          我也來頂一個(gè)。樓主好樣的。。。擾屏對(duì)不起樓主,頂下..本人自己開培訓(xùn)部,
          如果有感興趣的同學(xué),可以利用以下的聯(lián)系方式聯(lián)系我們,感謝大家的支持,歡迎咨詢
          福建省福州市戰(zhàn)虎軟件研發(fā)中心俱樂部===火熱報(bào)名中……
          戰(zhàn)虎軟件研發(fā)中心俱樂部歡迎您:走在軟件開發(fā)安全的最前沿
          本培訓(xùn)中心選修課程如下:
          企業(yè)軟件研發(fā) 軟件架構(gòu)設(shè)計(jì) SQL注入 遠(yuǎn)程控制 木馬研究 2D游戲研發(fā) 3D游戲研究 外掛研究 3D游戲研究 數(shù)據(jù)庫(kù)設(shè)計(jì)
          涉及的語言有:ASP.NET-C#......JAVA……C++……MASM32……PHP……FLASH AS3
          地址:福建省福州市倉(cāng)山區(qū)福建師范大學(xué)附近
          如要咨詢?cè)斍椋瑩艽螂娫挘?5005086322進(jìn)行咨詢
          聯(lián)系方式:張老師15005086322|QQ:張老師920358479,張助理364823620
          Email:zse555@fight-tiger.com|網(wǎng)址:http://www.fight-tiger.com
            回復(fù)  更多評(píng)論   

          # re: 使用commons-fileupload實(shí)現(xiàn)單個(gè)和多個(gè)文件上傳[未登錄] 2009-03-17 21:47 1

          so good!~~  回復(fù)  更多評(píng)論   

          # re: 使用commons-fileupload實(shí)現(xiàn)單個(gè)和多個(gè)文件上傳 2009-08-06 18:53 help

          UploadUtil 在那里定義的?怎么找不到,能把代碼貼出來嗎  回復(fù)  更多評(píng)論   

          # re: 使用commons-fileupload實(shí)現(xiàn)單個(gè)和多個(gè)文件上傳 2009-09-08 17:59 miffy

          寫的很詳細(xì),謝謝分享!  回復(fù)  更多評(píng)論   

          # re: 使用commons-fileupload實(shí)現(xiàn)單個(gè)和多個(gè)文件上傳 2009-10-24 15:21 roundzheng

          很不錯(cuò),真的我調(diào)試了,很成功!  回復(fù)  更多評(píng)論   

          # re: 使用commons-fileupload實(shí)現(xiàn)單個(gè)和多個(gè)文件上傳[未登錄] 2010-03-31 16:41 df

          ff  回復(fù)  更多評(píng)論   

          # re: 使用commons-fileupload實(shí)現(xiàn)單個(gè)和多個(gè)文件上傳[未登錄] 2010-03-31 16:42 df

          fdfd  回復(fù)  更多評(píng)論   

          # re: 使用commons-fileupload實(shí)現(xiàn)單個(gè)和多個(gè)文件上傳[未登錄] 2010-03-31 16:42 df











































































































































































































          fdfd



          dfd
            回復(fù)  更多評(píng)論   

          # re: 使用commons-fileupload實(shí)現(xiàn)單個(gè)和多個(gè)文件上傳 2012-12-13 10:37 存儲(chǔ)

          @help
          。。。我也想知道這個(gè)問題  回復(fù)  更多評(píng)論   

          sitinspring(http://www.aygfsteel.com)原創(chuàng),轉(zhuǎn)載請(qǐng)注明出處.
          主站蜘蛛池模板: 筠连县| 郴州市| 汕尾市| 新巴尔虎左旗| 汉沽区| 奉节县| 龙门县| 离岛区| 嫩江县| 扶余县| 祁东县| 儋州市| 陆良县| 辰溪县| 红安县| 古丈县| 新昌县| 霸州市| 云南省| 得荣县| 衡阳市| 石屏县| 延津县| 佳木斯市| 宜春市| 乌鲁木齐市| 孙吴县| 黄龙县| 虹口区| 祥云县| 伊金霍洛旗| 甘肃省| 苏尼特右旗| 嘉义市| 郓城县| 开阳县| 麻栗坡县| 行唐县| 满洲里市| 湘西| 同心县|