java中Struts2 的檔案上傳和下載樣本_java

來源:互聯網
上載者:User

檔案上傳

  1. 表單準備
    • 要想使用 HTML 表單上傳一個或多個檔案
    • 須把 HTML 表單的 enctype 屬性設定為 multipart/form-data
    • 須把 HTML 表單的method 屬性設定為 post
    • 需添加 <input type=“file”> 欄位.
  2. Struts 對檔案上傳的支援
    • 在 Struts 應用程式裡, FileUpload 攔截器和 Jakarta Commons FileUpload 組件可以完成檔案的上傳.
    • 步驟:
      1. 在 Jsp 頁面的檔案上傳表單裡使用 file 標籤. 如果需要一次上傳多個檔案, 就必須使用多個 file 標籤, 但它們的名字必須是相同的
      2. 在 Action 中新添加 3 個和檔案上傳相關的屬性. 這 3 個屬性的名字必須是以下格式
        • 基本的檔案的上傳: 直接在 Action 中定義如下 3 個屬性, 並提供對應的 getter 和 setter
        • [File Name] : 類型-File -被上傳的檔案。例如:data(fileName要求和檔案表單項的name一致)
        • [File Name]ContentType : 類型-String -上傳檔案的檔案類型。例如:dataContentType(用來接收檔案類型(MIME值))
        • [File Name]FileName : String -上傳檔案的檔案名稱。例如:dataFileName (用來接收檔案的名字)
      3. 如果上傳多個檔案, 可以使用 List
        • 若傳遞多個檔案, 則上述的 3 個屬性, 可以改為 List 類型! 多個檔案域的 name 屬性值需要一致.
  3. 範例程式碼
<s:form action="testUpload" enctype="multipart/form-data">  <s:textfield name="userName[0]" label="使用者-1"></s:textfield>  <s:file name="photos" label="照片"></s:file>  <s:textfield name="userName[1]" label="使用者-2"></s:textfield>  <s:file name="photos" label="照片"></s:file>  <s:textfield name="userName[2]" label="使用者-3"></s:textfield>  <s:file name="photos" label="照片"></s:file>  <s:submit value="提交"></s:submit></s:form> 
public class UploadAction extends ActionSupport{  @Setter@Getter  private List<File> photos;  @Setter@Getter  private List<String> photosContentType;  @Setter@Getter  private List<String> photosFileName;  @Setter@Getter  private List<String> userName;  public String testUpload() throws IOException {    System.out.println("userName: "+userName);    System.out.println("photos: "+photos);    System.out.println("photosFileName: "+ photosFileName);    System.out.println("photosContentType: "+photosContentType);    // 將檔案傳到伺服器根目錄下upload檔案下    // 擷取ServletContext    ServletContext servletContext = ServletActionContext.getServletContext();    //擷取真實路徑    String realPath = servletContext.getRealPath("/upload");    System.out.println(realPath);    File uploadFile = new File(realPath);    //判斷路徑是否存在    if (!uploadFile.exists()){      //不存在建立      uploadFile.mkdir();    }    for (int i = 0; i < photos.size(); i++) {      UUID uuid = UUID.randomUUID();      FileUtils.copyFile(photos.get(i), new File(realPath + "/" + uuid + photosFileName.get(i)));    }    return SUCCESS;  }}

1.處理幾個小問題?

1.檔案名稱重名,一般可以在檔案名稱的前面產生一個UUID作為首碼。

2.限制單個檔案的大小

3.限制檔案的類型

4.限制總檔案的大小

2.在Struts2 中提供了 FileUpload 攔截器 可以給我們設定這些屬性值

 FileUpload 攔截器有 3 個屬性可以設定.

  •  maximumSize: 上傳單個檔案的最大長度(以位元組為單位), 預設值為 2 MB
  • allowedTypes: 允許上傳檔案的類型, 各類型之間以逗號分隔
  • allowedExtensions: 允許上傳副檔名, 各副檔名之間以逗號分隔
  • 可以在 struts.xml 檔案中覆蓋這 3 個屬性

注意: 在 org.apache.struts2 下的 default.properties 中有對上傳的檔案總的大小的限制. 可以使用常量的方式來修改該限制struts.multipart.maxSize=2097152

<constant name="struts.devMode" value="true"/> <!-- 在這修改總檔案的的大小 --> <constant name="struts.multipart.maxSize" value="2097152"/> <package name="default" namespace="/" extends="struts-default">  <interceptors>    <interceptor-stack name="myInterceptor">      <interceptor-ref name="defaultStack">        <!-- 修改單個檔案大小,Commons FileUpload 組件預設接受上傳檔案總的最大值為 2M -->        <param name="fileUpload.maximumSize">57,408</param>        <!-- 允許上傳的檔案類型 -->        <param name="fileUpload.allowedTypes">image/pjpeg,image/gif</param>        <!-- 允許上傳檔案的副檔名 -->        <param name="fileUpload.allowedExtensions">jpg,gif</param>      </interceptor-ref>    </interceptor-stack>  </interceptors>  <default-interceptor-ref name="myInterceptor"></default-interceptor-ref>    <action name="testUpload" class="org.pan.action.UploadAction" method="testUpload">    <result name="success">/WEB-INF/views/success.jsp</result>    <result name="input">/upload.jsp</result>  </action></package>

一.上傳檔案相關的錯誤訊息?

1.與檔案上傳有關的出錯訊息在 struts-messages.properties 檔案裡預定義.

2.可以在檔案上傳 Action 相對應的資源檔 或者 在 i18n_zh_CN.properties 國際化資源檔中重新定義錯誤訊息

struts.messages.error.file.too.large=你傳的檔案太大了struts.messages.error.content.type.not.allowed=檔案類型錯誤struts.messages.error.file.extension.not.allowed=副檔名錯誤struts.messages.upload.error.SizeLimitExceededException=檔案總大小超過上限

檔案下載

  1. 在某些應用程式裡, 可能需要動態地把一個檔案發送到使用者的瀏覽器中, 而這個檔案的名字和存放位置在編程時是無法預知的

  2. Stream 結果類型
    • Struts 專門為檔案下載提供了一種 Stream 結果類型. 在使用一個 Stream 結果時, 不必準備一個 JSP 頁面.
    • Stream 結果類型可以設定如下參數:
      • contentType:被下載的檔案的 MIME 類型。預設值為 text/plain
      • contentLength:被下載的檔案的大小,以位元組為單位
      • contentDisposition: 可以設定下載檔案名稱的ContentDispositon 回應標頭,預設值為 inline,通常設定為如下格式:
        • attachment;filename="document.pdf".
      • inputName:Action 中提供的檔案的輸入資料流。預設值為 inputStream
      • bufferSize:檔案下載時緩衝區的大小。預設值為 1024
      • allowCaching :檔案下載時是否允許使用緩衝。預設值為 true
      • contentCharSet:檔案下載時的字元編碼。
        • 以上參數可以在 Action 中以 getter 方法的方式提供!
    • Stream 結果類型的參數可以在 Action 以屬性的方式覆蓋
    • 具體使用細節參看 struts-2.3.15.3-all/struts-2.3.15.3/docs/WW/docs/stream-result.html
  3. 範例程式碼

<a href="testDownLoad">下載</a>
public class DownLoadAction extends ActionSupport{  //通常以下這幾個參數會在Action 中提供  @Setter@Getter  private String contentType;  @Setter@Getter  private long contentLength;  @Setter@Getter  private String contentDisposition;  @Setter@Getter  private InputStream inputStream;  public String testDownLoad() throws FileNotFoundException, UnsupportedEncodingException {    //擷取ServletContext    ServletContext servletContext = ServletActionContext.getServletContext();    //擷取檔案的路徑    String realPath = servletContext.getRealPath("/WEB-INF/file/至少還有你.mp3");    //擷取檔案的流    inputStream = new FileInputStream(realPath);    //設定檔案的類型    contentType = servletContext.getMimeType(realPath);    //擷取檔案的長度    contentLength = new File(realPath).length();    //設定檔案名稱    String fileName = "至少還有你.mp3";    fileName = new String(fileName.getBytes("gbk"),"iso8859-1");    contentDisposition = "attachment;filename="+fileName;    return SUCCESS;  }}
<!-- 檔案下載 --><action name="testDownLoad" class="org.pan.action.DownLoadAction" method="testDownLoad">  <result type="stream">    <!-- 檔案緩衝大小 -->    <param name="bufferSize">2048</param>  </result></action>

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.