我们已经知道了许许多多种类的处理文件上传的代码,比较典型的比如Apache大名鼎鼎的FileUpload等,当然了, Liferay为我们都考虑过了,我们可以用Liferay自带的上传文件的API来处理文件上传问题,这个核心接口就是com.liferay.portal.kernel.upload.UploadPortletRequest接口。
举个最简单的例子,比如我们要在Portlet页面上传一个文件到Portlet中,然后Portlet吧这个文件移动到别的位置:
那么,在页面上(比如config.jsp)中,我们必须用一个<input type="file">来表示一个文件上传控件:
- <td>
- <label><liferay-ui:message key="rslaunch.zipfile" /></label>
- <div>
- <input class="lfr-input-text" name="Zip" type="file" />
- <input name="<portlet:namespace /><%=Constants.CMD %>" type="hidden" value="<%=Constants.UPDATE%>" />
- </div>
- </td>
然后,在我们java代码中,我们利用UploadPortletRequest接口来处理被上传的文件:
- /**
- * Method used to upload the file on the target by reading the server details from the properties
- * @param actionRequest
- * @throws Exception
- */
- public static void uploadFileToDest(ActionRequest actionRequest) throws Exception{
- if(LOGGER.isDebugEnabled()){
- LOGGER.debug("FileOperationHelper : uploadFileToDest()");
- }
- PortletPreferences preferences = PortletHelper.getPortletPreferences(actionRequest);
- String portletInstanceId = preferences.getValue(RS_LAUNCH_PORTLET_PREFERENCE_PORTLET_ID, StringPool.DOUBLE_QUOTE);
- String fileOriginFolder = configUtil.getProperty(RS_LAUNCH_ZIP_ORIGIN_FOLDER);
- UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
- String fileName = uploadRequest.getFileName(RS_LAUNCH_CONFIG_PAGE_FORM_ZIP_INPUT_NAME);
- File tempFile = uploadRequest.getFile(RS_LAUNCH_CONFIG_PAGE_FORM_ZIP_INPUT_NAME);
- ...
从这里代码可以看出来,我们在第15行获取一个UploadPortletrequest对象,然后用它的AP就可以正确的获取文件名字(16行)和获取文件对象了,接下来对于这个文件的操作就是普通的I/O操作,我们这里就略去了。
转载于:https://blog.51cto.com/supercharles888/989530