筆記:Struts2 檔案上傳和下載

來源:互聯網
上載者:User

標籤:mime   mkdir   ref   type   utf-8   get   響應   cache   set   

為了上傳檔案必須將表單的method設定為POST,將 enctype 設定為 muiltipart/form-data,只有設定為這種情況下,瀏覽器才會把使用者選擇檔案的位元據發送給伺服器。

  1. 上傳解析器配置
    1. Struts2 沒有提供自己的請求解析器,struts2 需要調用其他上傳架構來解析位元據,struts2 預設使用 jakarta 的 Common-FileUpload 的檔案上傳架構,需要在 Web 應用的 lib 中增加 commons-io-2.2.jar 和 commons-fileupload-1.3.2.jar。
    2. 通過 struts2 的常量配置 struts.multipart.parser 來設定檔案上傳解析器,預設值 jakarta
    3. Struts.multipart.saveDir:上傳檔案的臨時檔案儲存路徑,預設值 javax.servlet.context.tempdir 配置的路徑,該路徑是Tomcat的安裝路徑下的 work\Catalina\localhost
    4. Struts.multipart.maxSize:整個表單請求內容的最大位元組數,預設值 2097152
  2. 上傳Action 解析
    1. 建立 java.io.File 類型的欄位來接收上傳的檔案流;建立 xxxFileName 和 xxxContentType 來讀取原始上傳的檔案名稱和檔案類型,其中 xxx 表示的是 java.io.File 類型的欄位名稱,比如樣本是名為 upload 欄位接收上傳的檔案流,因此需要有 uploadFileName 和 uploadContentType 來接收該檔案流的原始檔案名稱和檔案類型,範例程式碼如下:

      ??

      public class UploadAction extends ActionSupport {

      ??

      /**

      *

      */

      private static final long serialVersionUID = 283051583917637792L;

      ??

      private File upload;

      private String uploadFileName;

      private String uploadContentType;

      private String uploadPath;

      ??

      public UploadAction() {

      uploadPath = "upload";

      }

      ??

      @Override

      public String execute() throws Exception {

      ??

      if (upload == null) {

      addActionError("沒有選擇上傳檔案");

      return INPUT;

      }

      ??

      String filePath = ServletActionContext.getServletContext().getRealPath(uploadPath);

      ??

      java.io.File dir = new java.io.File(filePath);

      if (dir.exists() == false) {

      if (dir.mkdirs() == false) {

      addActionError("建立目錄失敗,目錄路徑=" + filePath);

      return INPUT;

      }

      }

      ??

      System.out.println("Upload FileName =" + uploadFileName);

      System.out.println("Upload ContentType =" + uploadContentType);

      ??

      FileOutputStream fileOutputStream = new FileOutputStream(filePath + File.pathSeparator + uploadFileName);

      FileInputStream fileInputStream = new FileInputStream(upload);

      byte[] buffer = new byte[4096];

      int len = 0;

      do {

      len = fileInputStream.read(buffer, 0, buffer.length);

      if (len > 0) {

      fileOutputStream.write(buffer, 0, len);

      }

      } while (len > 0);

      ??

      addActionMessage("上傳完成,儲存路徑=" + filePath + File.pathSeparator + uploadFileName);

      ??

      return SUCCESS;

      }

      ??

      public File getUpload() {

      return upload;

      }

      ??

      public void setUpload(File upload) {

      this.upload = upload;

      }

      ??

      public String getUploadFileName() {

      return uploadFileName;

      }

      ??

      public void setUploadFileName(String uploadFileName) {

      this.uploadFileName = uploadFileName;

      }

      ??

      public String getUploadContentType() {

      return uploadContentType;

      }

      ??

      public void setUploadContentType(String uploadContentType) {

      this.uploadContentType = uploadContentType;

      }

      }

  3. fileUpload 攔截器
    1. fileUpload 攔截器是struts2 提供的一個檔案上傳攔截器,用於攔截不允許的上傳檔案類型和檔案大小,需要配置二個參數來處理:
      1. 參數 allowedTypes:該參數指定允許上傳的檔案類型(contentType),多個檔案類型以英文逗號隔開
      2. 參數 maximumSize:該參數指定允許上傳的檔案大小,單位位元組
    2. 如果上傳檔案類型或者檔案大小錯誤,fileUpload 攔截器將會讀取全域國際化資源檔來進行提示,讀取的Key如下:
      1. struts.messages.error.file.too.large:該key表示上傳的檔案太大的提示
        1. {0} 表示 ActionName
        2. {1} 表示上傳原始檔案名稱
        3. {2} 表示伺服器臨時檔案名稱
        4. {3} 上傳檔案的 ContentType
      2. struts.messages.error.content.type.not.allowed:該key表示上傳檔案類型錯誤的提示
        1. {0} 表示 ActionName
        2. {1} 表示上傳原始檔案名稱
        3. {2} 表示伺服器臨時檔案名稱
        4. {3} 上傳檔案的位元組大小
        5. {4} 允許的上傳檔案位元組大小
      3. struts.messages.error.uploading:該key表示上傳檔案出現一個未知錯誤的提示
    3. 配置範例程式碼

      <action name="upload" class="org.drsoft.actions.file.UploadAction">

      <interceptor-ref name="fileUpload">

      <param name="allowedTypes">image/png</param>

      <param name="maximumSize">102400</param>

      </interceptor-ref>

      <!--必須增加該項,如果不增加其他的攔截器會預設增加該攔截器-->

      <interceptor-ref name="defaultStack"/>

    ??

    <result name="success">/WEB-INF/content/file/upload.jsp</result>

    <result name="input">/WEB-INF/content/file/upload.jsp</result>

    </action>

  4. 下載檔案 Action
    1. 下載檔案的Action需要使用 stream 的結果類型,stream結果類型需要指定一個 inputName 參數,該參數指定了一個輸入資料流,這個輸入資料流是被下載檔案的入口,詳細參數如下:
      1. 參數 inputName:表示其Action類的返回 InputStream 的下載方法名稱,樣本,設定為 downloadFile 則會調用 Action類的 getDownloadFile 方法
      2. 參數 contentType:設定 httpResponse 的 mime-type ,設定 response 的 contentType 頭,預設值 text/plain,通用值 application/octet-stream
      3. 參數 contentDisposition:設定響應報文頭的 content disposition 值,用於指定瀏覽器的處理方式和下載檔案名稱,預設類型為 inline(內聯),瀏覽器將會開啟檔案,可以設定 attachment(附件),瀏覽器將提示儲存檔案,參數樣本:Inline;filename="downloadfile.zip",如果檔案名稱為中文,則需要使用 java.net.URLEncoder.encode(fileName, "UTF-8")
      4. 參數 contentLength:設定流的位元組長度,用於瀏覽器的下載進度顯示
      5. 參數 bufferSize:輸入資料流和輸出資料流的緩衝區位元組大小
      6. 參數 allowCaching:如果設定為 false,會將 response 報文頭的 Cache-Control設定為no-cache,預設值 true
      7. 參數 contentCharSet:設定內容編碼,如果設定了值將會增加到x響應報文的 contentType 後面附加 ";charset=value"

        ??

    ??

??

筆記:Struts2 檔案上傳和下載

聯繫我們

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