單檔案上傳和多檔案上傳

來源:互聯網
上載者:User

J2EE開發各類資源下載清單,  史上最全IT資源,個人收藏總結。


1. 單檔案上傳:

struts-fileupload.xml

<struts>  <constant name="struts.configuration.xml.reload" value="true"></constant>  <!-- 限制了一次上傳檔案總數最大為10M,預設為2M       當單個檔案或檔案數組和大小大於2Mb時,會拋出org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException:    the request was rejected because its size (2667603) exceeds the configured maximum (2097152)   -->  <constant  name="struts.multipart.maxSize" value="10701096"></constant>  <package name="upload" namespace="/upload" extends="struts-default">     <action name="one" class="edu.action.OneFileUploadAction" method="singleFile">        <result name="onemessage">/page/uploadmessage.jsp</result>     </action>     <action name="many" class="edu.action.ManyFileUpload" method="manyFile">        <result name="manymessage">/page/manyfilemessage.jsp</result>     </action>  </package>  </struts>


OneFileUploadAction.java

package edu.action;import java.io.File;import java.io.IOException;import org.apache.commons.io.FileUtils;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionContext;public class OneFileUploadAction {private String userName;private File image;private String imageFileName;private String imageContentType;public String singleFile() throws IOException {    //將檔案儲存在/image/下,得到檔案的真實路徑String realPath = ServletActionContext.getServletContext().getRealPath("/image");if (image!=null){//得到上傳檔案路徑File imageFile = new File(new File(realPath),imageFileName);if (!imageFile.getParentFile().exists()) {imageFile.getParentFile().mkdirs(); //包含多級目錄建立}//struts在執行下句之前,會將上傳的檔案放進臨時目錄下,執行下句後,將臨時檔案copy進真實目錄下後,會remove掉臨時檔案FileUtils.copyFile(image, imageFile);ActionContext.getContext().put("message", "上傳成功!");//測試位元據下userName屬性是否亂碼System.out.println("上傳者:"+userName+",檔案名稱:"+imageFileName+",檔案類型:"+imageContentType+",狀態:上傳成功");}return "onemessage";}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getImageFileName() {return imageFileName;}//檔案名稱定義格式"File名+FileName"public void setImageFileName(String imageFileName) {this.imageFileName = imageFileName;}//與表單的<input type="file" name="image">屬性名稱相同public void setImage(File image) {this.image = image;}//檔案類型名稱定義格式"File名+ContentType"public void setImageContentType(String imageContentType) {this.imageContentType = imageContentType;}}
上傳成功後,控制台列印: 上傳者:肖華,檔案名稱:2012_03130103.JPG,檔案類型:image/jpeg,狀態:上傳成功

OneFileUpload.jsp

<body>    <form action="${pageContext.request.contextPath}/upload/one" enctype="multipart/form-data" method="post">       姓名:<input type="text" name="userName"><br/>      照片:<input type="file" name="image"><br/>      <input type="submit" value="regist">    </form>  </body>

uploadmessage.jsp

<body>      ${userName}:${imageFileName}:${message}  </body>

總結:

     第一步:在WEB-INF/lib下加入commons-fileupload-1.2.1.jar、commons-io-1.3.2.jar。這兩個檔案可以從http://commons.apache.org/下載。

     第二步:把form表的enctype設定為:“multipart/form-data“,如下:        <form action="${pageContext.request.contextPath}/upload/one"enctype="multipart/form-data" method="post">
         姓名:<input type="text" name="userName"><br/>
         照片:<input type="file" name="image"><br/>
            <input type="submit" value="regist">
       </form>

     第三步:在Action類中添加以下屬性,屬性紅色部分對應於表單中檔案欄位的名稱,屬性藍色部分是固定格式:

public class HelloWorldAction{

  private File uploadImage;//得到上傳的檔案

  private String uploadImageContentType;//得到檔案的類型

  private String uploadImageFileName;//得到檔案的名稱

  //這裡略省了屬性的getter/setter方法,提供了setter方法後,struts2會自動調用setter方法,為其賦值

       }

    注意:(1)struts預設一次性最大檔案上傳大小為2Mb,所以如果單個檔案或檔案數組之和大小大於2Mb的話,會拋出:org.apache.commons.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (2667603) exceeds the configured maximum (2097152)
    所以應該在struts.xml檔案中配置常量控制檔案上傳最大大小。

   <constant  name="struts.multipart.maxSize" value="10701096"></constant>

        (2)如果/image檔案下存在同名的檔案,則後者將覆蓋前者,而不會報告任何錯誤。

        (3)struts2對錶單的中文亂碼處理的很好,以及對enctype="multipart/form-data"表單中字元處理的很好,無需程式員手工處理。

2. 多檔案上傳:ManyFileUploadAction.java

   ManyFileUploadAction.java

package edu.action;import java.io.File;import java.io.IOException;import org.apache.commons.io.FileUtils;import org.apache.struts2.ServletActionContext;import com.opensymphony.xwork2.ActionContext;public class ManyFileUploadAction {    private String userName;    private File[] image; //這裡可以使用List或數組儲存    private String[] imageFileName;//這裡可以使用List或數組儲存   public String manyFile() throws IOException {       //將檔案儲存在/image/下,得到檔案的真實路徑        String realPath = ServletActionContext.getServletContext().getRealPath("/image");        if (image!=null)        {            //得到上傳檔案目錄            File imageDir = new File(realPath);            if (!imageDir.exists()) {                imageDir.mkdirs(); //包含多級目錄建立            }            for (int i = 0; i < image.length; i++) {                File imageFile = new File(imageDir,imageFileName[i]);                FileUtils.copyFile(image[i], imageFile);            }            ActionContext.getContext().put("count", image.length);        }       return "manymessage";   }    public String getUserName() {        return userName;    }    public void setUserName(String userName) {        this.userName = userName;    }    public String[] getImageFileName() {        return imageFileName;    }    public void setImageFileName(String[] imageFileName) {        this.imageFileName = imageFileName;    }    public void setImage(File[] image) {        this.image = image;    }}

manyFileUpload.jsp

  <body>    <form action="${pageContext.request.contextPath}/upload/many" enctype="multipart/form-data" method="post">       姓名:<input type="text" name="userName"><br/>      照片1:<input type="file" name="image"><br/>      照片2:<input type="file" name="image"><br/>      照片3:<input type="file" name="image"><br/>      <input type="submit" value="regist">    </form>  </body>

manyfilemessage.jsp

  <body>       使用者名稱:${userName},照片個數:${count}<br>   <c:forEach var="imageName" items="${imageFileName}">      ${imageName}:<img src="${pageContext.request.contextPath}/image/${imageName}" weight="200px" height="200px"/><br/>   </c:forEach>  </body>

 瀏覽器:

    

點擊regist按鈕:


這裡對於

<img src="${pageContext.request.contextPath}/image/${imageName}" weight="200px" height="200px"/>

如果檔案名稱包含中文時,則無法顯示,不知道為什麼。。 

總結:

     (1)對於多檔案上傳時,檔案文字框的name屬性須相同,在Action中多個檔案,可以用數組和List集合儲存。

     (2)沒有上傳檔案的檔案文字框,struts2不會將其傳給struts的Action,從上面的length=2可以看出。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.