我们已经知道了许许多多种类的处理文件上传的代码,比较典型的比如Apache大名鼎鼎的FileUpload等,当然了, Liferay为我们都考虑过了,我们可以用Liferay自带的上传文件的API来处理文件上传问题,这个核心接口就是com.liferay.portal.kernel.upload.UploadPortletRequest接口。

 

举个最简单的例子,比如我们要在Portlet页面上传一个文件到Portlet中,然后Portlet吧这个文件移动到别的位置:

那么,在页面上(比如config.jsp)中,我们必须用一个<input type="file">来表示一个文件上传控件:

 
  
  1. <td> 
  2.  
  3.      <label><liferay-ui:message key="rslaunch.zipfile" /></label> 
  4.  
  5.      <div> 
  6.  
  7.              <input class="lfr-input-text" name="Zip" type="file" /> 
  8.  
  9.              <input name="<portlet:namespace /><%=Constants.CMD %>" type="hidden" value="<%=Constants.UPDATE%>" /> 
  10.  
  11.       </div> 
  12.  
  13.  </td> 

 

然后,在我们java代码中,我们利用UploadPortletRequest接口来处理被上传的文件:

 
  
  1. /** 
  2.   * Method used to upload the file on the target by reading the server details from the properties 
  3.   * @param actionRequest 
  4.   * @throws Exception 
  5.   */ 
  6.          public static void uploadFileToDest(ActionRequest actionRequest) throws Exception{ 
  7.   
  8.                  if(LOGGER.isDebugEnabled()){ 
  9.                     LOGGER.debug("FileOperationHelper : uploadFileToDest()"); 
  10.               } 
  11.                  PortletPreferences preferences = PortletHelper.getPortletPreferences(actionRequest); 
  12.         String portletInstanceId = preferences.getValue(RS_LAUNCH_PORTLET_PREFERENCE_PORTLET_ID, StringPool.DOUBLE_QUOTE); 
  13.   
  14.                  String fileOriginFolder = configUtil.getProperty(RS_LAUNCH_ZIP_ORIGIN_FOLDER); 
  15.         UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest); 
  16.         String fileName = uploadRequest.getFileName(RS_LAUNCH_CONFIG_PAGE_FORM_ZIP_INPUT_NAME); 
  17.         File tempFile = uploadRequest.getFile(RS_LAUNCH_CONFIG_PAGE_FORM_ZIP_INPUT_NAME); 
  18.    ...

从这里代码可以看出来,我们在第15行获取一个UploadPortletrequest对象,然后用它的AP就可以正确的获取文件名字(16行)和获取文件对象了,接下来对于这个文件的操作就是普通的I/O操作,我们这里就略去了。