struts2 實現檔案上傳原理

來源:互聯網
上載者:User
struts2 實現檔案上傳原理

  通過struts2實現檔案上傳功能,主要jar包是不可少的包括:

aopalliance.jar  ------------------------------------為aop(面向切面)提供了最普通和通用的介面asm-3.3.jar  ----------------------------------------操作java位元組碼的類庫asm-commons-3.3.jar  --------------------------------提供了基於事件的表現形式commons-fileupload-1.2.2.jar  -----------------------實現struts檔案的上傳下載commons-io-2.0.1.jar  -------------------------------檔案上傳讀取檔案commons-lang3-3.1.jar  ------------------------------為java.lang包提供擴充commons-logging-1.1.1.jar  --------------------------jakarta的通用日誌記錄包freemarker-2.3.19.jar  ------------------------------FreeMarker是一個模板引擎,一個基於模板產生文本輸 出的通用工具javassist-3.11.0.GA.jar  ----------------------------Javassist是一個開源的分析、編輯和建立Java位元組碼的類庫ognl-3.0.5.jar  -------------------------------------標籤庫struts2-convention-plugin-2.3.3.jar  ----------------在預設情況下該公約外掛程式尋找操作類在以下軟體包支柱,struts2的行為或行動,任何包相匹配這些名稱將被考慮struts2-core-2.3.3.jar  -----------------------------strut2的核心處理包struts2-json-plugin-2.3.3.jar  ----------------------struts2所用到的json外掛程式包xwork-core-2.3.3.jar  -------------------------------webwork的核心庫

  1.  struts2沒有提供自己的請求解析器,也就是就struts2不會自己去處理multipart/form-data的請求,它需要調用其他請求解析器,將HTTP請求中的表單域解析出來。但struts2在原有的上傳解析器基礎上做了進一步封裝,更進一步簡化了檔案上傳。 

  2. struts2預設使用的是Jakarta的Common-FileUpload架構來上傳檔案,因此,要在web應用中增加Jar文 件:commons-fileupload-1.2.jar和commons-io-1.3.1.jar。它在原上傳架構上做了進一步封裝,簡化了檔案上傳的代碼實現,取消了不同上傳架構上的編程差異。 

  3. 如果要改成其它的檔案上傳架構,可以修改struts.multipart.parser或(struts.multipart.hander)常量的值為cos/pell,預設值是jakata。並在classpath中增加相應上傳組件的類庫。

  4. struts2所用的檔案上傳架構都是先將Http上傳的檔案儲存到臨時目錄下, 然後struts2通過FileUpload攔截器將檔案綁定到Action執行個體中。臨時目錄可以在struts.xml中配置,如果不配置則會將臨時檔案存在預設臨時目錄下(具體目錄忘記了。。)。也可以理解為struts2上傳檔案是通過Action完成的,而Action的工作主要是將緩衝目錄中的檔案複製到目的地址,在Action執行之前,系統已經將檔案上傳到伺服器的臨時目錄中了。

  5. struts2的檔案上傳工作都要通過FileUploadInterceptor,這個攔截器對檔案大小,檔案類型,檔案資訊進行了攔截設定,但是並沒有做IO的監控操作。 

貼出FileUploadInterceptor中的一段代碼:可以看出當http發出上傳請求時,是由MultiPartRequestWrapper類來提供檔案名稱及檔案元素的處理操作的。 1 public String intercept(ActionInvocation invocation) throws Exception { 2         ActionContext ac = invocation.getInvocationContext(); 3  4         HttpServletRequest request = (HttpServletRequest) ac.get(ServletActionContext.HTTP_REQUEST); 5  6         if (!(request instanceof MultiPartRequestWrapper)) { 7             if (LOG.isDebugEnabled()) { 8                 ActionProxy proxy = invocation.getProxy(); 9                 LOG.debug(getTextMessage("struts.messages.bypass.request", new String[]{proxy.getNamespace(), proxy.getActionName()}));10             }11 12             return invocation.invoke();13         }14 15         ValidationAware validation = null;16 17         Object action = invocation.getAction();18 19         if (action instanceof ValidationAware) {20             validation = (ValidationAware) action;21         }22 23         MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;24 25         if (multiWrapper.hasErrors()) {26             for (String error : multiWrapper.getErrors()) {27                 if (validation != null) {28                     validation.addActionError(error);29                 }30             }31         }32 33         // bind allowed Files34         Enumeration fileParameterNames = multiWrapper.getFileParameterNames();35         while (fileParameterNames != null && fileParameterNames.hasMoreElements()) {36             // get the value of this input tag37             String inputName = (String) fileParameterNames.nextElement();38 39             // get the content type40             String[] contentType = multiWrapper.getContentTypes(inputName);41 42             if (isNonEmpty(contentType)) {43                 // get the name of the file from the input tag44                 String[] fileName = multiWrapper.getFileNames(inputName);45 46                 if (isNonEmpty(fileName)) {47                     // get a File object for the uploaded File48                     File[] files = multiWrapper.getFiles(inputName);49                     if (files != null && files.length > 0) {50                         List<File> acceptedFiles = new ArrayList<File>(files.length);51                         List<String> acceptedContentTypes = new ArrayList<String>(files.length);52                         List<String> acceptedFileNames = new ArrayList<String>(files.length);53                         String contentTypeName = inputName + "ContentType";54                         String fileNameName = inputName + "FileName";55 56                         for (int index = 0; index < files.length; index++) {57                             if (acceptFile(action, files[index], fileName[index], contentType[index], inputName, validation)) {58                                 acceptedFiles.add(files[index]);59                                 acceptedContentTypes.add(contentType[index]);60                                 acceptedFileNames.add(fileName[index]);61                             }62                         }63 64                         if (!acceptedFiles.isEmpty()) {65                             Map<String, Object> params = ac.getParameters();66 67                             params.put(inputName, acceptedFiles.toArray(new File[acceptedFiles.size()]));68                             params.put(contentTypeName, acceptedContentTypes.toArray(new String[acceptedContentTypes.size()]));69                             params.put(fileNameName, acceptedFileNames.toArray(new String[acceptedFileNames.size()]));70                         }71                     }72                 } else {73                     if (LOG.isWarnEnabled()) {74                         LOG.warn(getTextMessage(action, "struts.messages.invalid.file", new String[]{inputName}));75                     }76                 }77             } else {78                 if (LOG.isWarnEnabled()) {79                     LOG.warn(getTextMessage(action, "struts.messages.invalid.content.type", new String[]{inputName}));80                 }81             }82         }83 84         // invoke action85         return invocation.invoke();86     }

   6. 繼續深入,MartiPartRequestWarpper對MartiPartRequest介面的主要功能進行的封裝應用,因此要繼續深入到MartiPartRequest介面的實作類別,可以瞭解到struts2是如何對檔案上傳進行控制操作的。

 1 MartiPartRequestWrapper的構造方法: 2  3 public MultiPartRequestWrapper(MultiPartRequest multiPartRequest, HttpServletRequest request, String saveDir, LocaleProvider provider) { 4         super(request); 5         errors = new ArrayList<String>(); 6         multi = multiPartRequest; 7         defaultLocale = provider.getLocale(); 8         setLocale(request); 9         try {10             multi.parse(request, saveDir);11             for (String error : multi.getErrors()) {12                 addError(error);13             }14         } catch (IOException e) {15             if (LOG.isWarnEnabled()) {16                 LOG.warn(e.getMessage(), e);17             }18             addError(buildErrorMessage(e, new Object[] {e.getMessage()}));19         } 20     }

  7. 從上面的代碼中可以知道,MultiPartRequest提供了主要的功能架構,JarkatMultiPartRequest是MultiPartRequest的實作類別,對檔案上傳具體功能進行了封裝。可以通過改寫此類實現對檔案上傳進度的監控,實現進度條功能(在後面的知識中詳細介紹進度條功能的實現)。

  在JarkatMultiPartRequest源碼中提供了方法parse(HttpServletRequest request, String saveDir),通過調用progressUpload(HttpServletRequest request, String saveDir)對檔案上傳進度進行控制。在其中通過DiskFileItemFactory、 ServletFileUpload對上傳檔案進行載入,並讀取。

聯繫我們

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