Struts2文件上傳實例

jopen 9年前發布 | 24K 次閱讀 Struts2 Web框架

1、實現struts2的文件上傳,首先把表單form的enctype屬性設置為:multipart/form-data


<form action="FileUpload" method="post" enctype="multipart/form-data">
            文件標題:<input name="title" type="text" /><br>
            文件:<input name="upload" type="file"/><br>
            <input type="submit" value="上傳" />
        </form>

2、然后添加FileUploadAction,其中有幾個屬性:upload、uploadFileName、uploadContentType、savePath,其中upload屬性為File類型,action類直接通過File類型屬性來封裝上傳的文件內容,struts2直接把上傳的文件名以及文件類型的信息封裝在xxxFileName和xxxContentType中,而savePath則是通過struts.xml配置文件中配置的路徑


action類為:


public class FileUploadAction {
    private String title;
    private File upload;
    private String uploadFileName;
    private String uploadContentType;
    private String savePath;             (getter/setter)
public String execute() throws Exception {
        System.out.println("path:" + getSavePath());
        System.out.println("filename:" + getUploadFileName());
        String path = ServletActionContext.getServletContext().getRealPath(getSavePath());// 相對路徑
        try {
            FileOutputStream fos = new FileOutputStream(path + "\\" + getUploadFileName());
            byte[] buffer = new byte[1024];
            int len;
            FileInputStream fis = new FileInputStream(getUpload());
            while ((len = fis.read(buffer)) > 0) {
                fos.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "success";
    }
}
這里要注意的是,如果struts配置文件中savePath配置的是相對路徑的話,則需要通過
String path = ServletActionContext.getServletContext().getRealPath(getSavePath());
來獲取相對路徑,如果是絕對路徑的話,可直接使用

FileOutputStream fos = new FileOutputStream(<span style="font-family: Arial, Helvetica, sans-serif;">getSavePath()</span> + "\\" + getUploadFileName());


3、添加上傳成功后轉向的頁面


上傳成功!
        <br>
        文件標題:
        <s:property value="title" />
        <br />
        文件為:
        <img src="<s:property value="'upload/'+uploadFileName"/>" />
        <br />

這里以顯示圖片為例



4、最后是配置action


<action name="FileUpload" class="com.demo.action.FileUploadAction">
            <!-- 動態設置action屬性值 -->
            <param name="savePath">/upload</param>
            <result name="success">/demo/jsp/uploadSuccess.jsp</result>
        </action>
這里配置的是相對路徑,需要在項目WebRoot下建立upload文件夾



5、最后在web.xml里配置一個Filter,ActionContextCleanUp,作用是方便struts2和SiteMesh整合,其實本來和文件上傳沒有什么關系,但發現有時候會出現一些未知的異常,但加了這個Filter后就一切正常了


<filter>
        <filter-name>struts-cleanup</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
    </filter>
<filter-mapping>
        <filter-name>struts-cleanup</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>


但啟動是后臺出現了錯誤

***

  •                                 WARNING!!!                              *
  •                                                                         *
  • >>> ActionContextCleanUp <<< is deprecated! Please use the new filters! *
  •                                                                         *
  •             This can be a source of unpredictable problems!             *
  •                                                                         *
  •                Please refer to the docs for more details!               *
  •              http://struts.apache.org/2.x/docs/webxml.html              *
  •                                                                        
    **
    </p>

    由于在struts升級時這個配置有漏洞,所以用以下配置代替


    <filter>

      <filter-name>struts-prepare</filter-name>
       <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter</filter-class>
    

    </filter> <filter-mapping>

       <filter-name>struts-prepare</filter-name>
       <url-pattern>/*</url-pattern>
    

    </filter-mapping>

    <filter>

       <filter-name>struts-execute</filter-name>
       <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter</filter-class>
    

    </filter> <filter-mapping>

       <filter-name>struts-execute</filter-name>
       <url-pattern>/*</url-pattern>
    

    </filter-mapping></pre>




    這里遇到一個問題,當上傳的文件名為中文時,會出現亂碼的情況,只需要在struts.xml中配置


    <!-- 設置應用使用的解碼集 -->
      <constant name="struts.i18n.encoding" value="UTF-8"/>

    接著,又出現上傳文件出錯了,原來是struts2對上傳的文件大小默認作了限制為2M,我們可以通過配置struts.xml來修改大小


    <!-- 修改默認文件上傳大小 -->
      <constant name="struts.multipart.maxSize" value="52428800"/>

    value處只能為計算的最終值,不能寫成value="1024102450"


    有時,我們要限制上傳的文件類型,可以配置fileUpload的攔截器

    在struts的action配置里添加攔截器,配置允許上傳的類型,這里一定要配置默認的攔截器,同時配置input的result,當出錯時返回原頁面并提示錯誤


    <interceptor-ref name="fileUpload">

              <param name="allowedTypes">image/jpeg,image/gif,image/png,application/pdf</param>
              <param name="maximumSize">52428800</param>
          </interceptor-ref>
          <interceptor-ref name="defaultStack"></interceptor-ref></pre>我們需要多添加個國際化信息文件message_zh_CN.properties,用以配置錯誤信息 <p><br />
    

    </p>


    struts.messages.error.content.type.not.allowed=the content type of file is not allowed
    struts.messages.error.file.too.large=file too large
    struts.messages.error.uploading=some false is unknown
    并在struts配置文件中添加



    <!-- 添加國際化信息 -->
      <constant name="struts.custom.i18n.resources" value="message"/>



    多文件上傳

    多文件上傳其實也很簡單,action中原來的屬性改為數組類型或者List類型,這里改為List類型


    public class MultiUploadAction extends ExampleSupport {
      private String title;
      private List<File> upload;
      private List<String> uploadFileName;
      private List<String> uploadContentType;
      private String savePath;

      (getter/setter)
      public String execute() {
      List<File> fileList = getUpload();
      String path = ServletActionContext.getServletContext().getRealPath(getSavePath());
      try {
          for (int i = 0; i < fileList.size(); i++) {
              FileOutputStream fos = new FileOutputStream(path + "\\" + getUploadFileName().get(i));
              byte[] buffer = new byte[1024];
              int len;
              FileInputStream fis = new FileInputStream(getUpload().get(i));
              while ((len = fis.read(buffer)) > 0) {
                  fos.write(buffer, 0, len);
              }
          }
      } catch (Exception e) {
          e.printStackTrace();
          return INPUT;
      }
      return SUCCESS;
    

    } }</pre>同時頁面也添加多幾個file類型的input即可



    <s:form action="MultiUpload" method="post" enctype="multipart/form-data">

      文件描述:<input name="title" type="text"/><br/>
      第一個文件:<input name="upload" type="file"/><br/>
      第二個文件:<input name="upload" type="file"/><br/>
      第三個文件:<input name="upload" type="file"/><br/>
      <s:submit value="上傳"/>
    

    </s:form></pre>


    來自:http://blog.csdn.net/kevinxxw/article/details/46988337


 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!