struts(檔案上傳與下載)

來源:互聯網
上載者:User

標籤:

檔案上傳:

1. Struts2預設採用了apache commons-fileupload。需要引入commons-fileupload相關依賴包:

    * commons-io-1.3.2.jar

    * commons-fileupload-1.2.1.jar

2. 表單中需要採用POST提交方式,編碼類別型需要使用:multipart/form-data

3. Struts2中Action相關屬性命名規則:

    取得檔案名稱->>規則:輸入欄位的名稱+固定字串"FileName",String類型。

    取得檔案資料->>規則:File 輸入欄位的名稱,File類型。

    取得內容類型->>規則:輸入欄位的名稱+固定字串"ContentType"。String類型。


     <form action="testUpload.action" method="post" enctype="multipart/form-data">

             <input type="file" name="file">

            <input type="submit" value="upload">

     </form>

      private File file;//檔案對應頁面name名稱

      private String fileContentType;//檔案類型

      private String fileFileName;//檔案名稱

4. 得到輸入資料流,採用輸出資料流寫檔案(action中方法):     

     public String execute() throws Exception {            InputStream is = null;            OutputStream os = null;            try {                is = new BufferedInputStream(new FileInputStream(file));                os = new BufferedOutputStream(new FileOutputStream("c:\\" + fileFileName));                byte[] buffer = new byte[1024];                int len = 0;                while ((len = is.read(buffer)) > 0) {                    os.write(buffer, 0, len);                }            }finally {                if (is != null) {is.close();}                if (os != null) {os.close();}            }            return Action.SUCCESS;     }

5. 若想對上傳檔案進行限制,可以配置攔截器:    

<!-- 配置上傳大小 -->關注   <constant name="struts.multipart.maxSize" ="20971520"></constant>   <interceptor-ref name="fileUpload">       <!-- 上傳檔案最大值 -->            <param name="maximumSize">20971520</param>              <!-- 允許類型 -->              <param name="allowedTypes">image/jpeg,image/gif,image/bmp</param>   </interceptor-ref>    

6. 不使用fileupload的攔截器攔截不允許的檔案類型:    

   1). 檔案上傳:設定不允許上傳的檔案類型         <package name="struts2" extends="struts-default" namespace="/">                       <action name="testUpload" class="com.mumu.action.TestAction" method="upload">                       <result>/index.jsp</result>                       <result name="input">/error.jsp</result>                       <param name="notAllowedTypes">image/jpeg,image/jpg</param>           // 關注                    </action>                 </package>       2). 通過方法判斷:         public String filterDocType(String[] types){                        //擷取檔案類型                        String fileType = this.getFileContentType();                        //遍曆類型                        for(String type:types){                            if(type.equals(fileType))                                return INPUT;                        }                        return null;             }       3). 檔案上傳時先判斷類型:       public String upload() throws IOException{                                            String filterResult = this.filterDocType(this.getNotAllowedTypes().split(","));關注                                        if(filterResult!=null){                                  //關注                        ActionContext.getContext().put("typeError","類型上傳不允許");                        return filterResult;                    }                  (看第6個,第6個代碼)                上傳檔案代碼..... (上傳資料庫過程中可以為檔案設定新名稱等)                //使用日期作為新名稱                    String u = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());                    //擷取副檔名稱                    String exename = this.fileFileName.substring(fileFileName.lastIndexOf("."));                    t_picture.setOldName(fileFileName);                    String newname = u+exename;                    t_picture.setNewName("upload/"+newname);                    //將資料存入資料庫                    dao.save(user);                    //檔案資料輸入流                    InputStream in = new FileInputStream(file);                    //上傳後檔案存放的路徑                    String path = ServletActionContext.getServletContext().getRealPath("/upload");                }    

7. 儲存檔案時應該儲存上傳的檔案名稱和真正存放時的檔案名稱。

8. 可以一次有多個上傳框一起上傳檔案。多檔案上傳文字框名字必須一樣,放在同一個form裡面。action中定義一個數組,名字為上傳檔案文字框的名字。

9. 預設上傳大小為2M。

10. struts:將檔案儲存到saveDir目錄下,然後從該目錄下以IO的形式讀到指定的目錄下。所以file指向的是saveDir目錄下的檔案。檔案file.getName()

     得到的是檔案在緩衝中的名字,也就是saveDir下的名字。

 

檔案下載:

1. 設定檔中result的類型必須<result type="stream">

2. 配置屬性:    

      <action name="testDownload" class="com.mumu.action.TestAction" method="download">                <result type="stream">                           <!-- 表示強制彈出提示框,下載的檔案(包含路徑) -->                    <!-- 通過el運算式,動態獲得下載時下載框顯示的名字。-->                    <!-- attachment表示不管能不能開啟,都要開啟下載對話方塊。預設為內聯,                         就是瀏覽器能開啟就開啟。                    --!>                       <param name="contentDisposition">attachment;filename=${filename}</param>                       <!-- 在類中要有一個get方法來對應inputStream,且傳回型別為inputStream                      action中對應的方法名get+裡面的參數名(如:download對應的是getDownload)                     inputName是固定的 -->                       <param name="inputName">inputStream</param>                                      <!-- 檔案下載的大小 -->                       <param name="bufferSize">1024</param>               </result>               <result name="input">/error.jsp</result>           </action>    

3. 錯誤:java.lang.IllegalArgumentException: Can not find a java.io.InputStream with the name [inputStream] in the invocation stack.

             Check the <param name="inputName">

    第一個原因:<param name="inputName">inputStream</param>在類中沒有對應的public InputStream getInputStream()方法

    第二種原因:檔案不存在

    第三種原因:檔案的路徑不對

 

4. 檔案下載需要寫的兩個方法(action中):    

       /**         * 檔案下載         */        public String download(){            return SUCCESS;        }        /**         * 檔案下載流,傳回值必須是InputStream。         * filename必須包含完整的檔案路徑。filename是從web項目開始,向下的路徑。如:webroot下有一個upload裡,放著下載的檔案。       */        public InputStream getInputStream(){            return ServletActionContext.getServletContext().getResourceAsStream(filename);        } 

5. 中文下載亂碼的一種解決方式:

    this.fileName="資料大全.txt";

    this.fileName=new String(this.fileName.getByte("gbk"),"8859_1");

 

struts(檔案上傳與下載)

聯繫我們

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