在开发Liferay portlet时,有时您需要使用文件工件.例如,您可能希望拥有可配置的映像,或者让用户将文件附加到自定义服务实体的方法.
Liferay内置了几个API来解决这个问题.每个人如何使用?
以下是我可以想到的三种存储和检索文件的方法.
存储:
使用DLStoreUtil您在问题中显示的方法.
检索:
为此,您需要将文件作为流获取,然后使用以下代码将其发送到浏览器:
String path = fileName;
// if there is a directory then path would be
// String path = "mydirectory/mySubDirectory/" + fileName; // mydirectory/mySubDirectory/my_File_image_name.png
InputStream inputStream = DLStoreUtil.getFileAsStream(companyId(), CompanyConstants.SYSTEM, path);
long contentLength = DLStoreUtil.getFileSize(companyId(), CompanyConstants.SYSTEM, path);
String contentType = MimeTypesUtil.getContentType(fileName);
ServletResponseUtil.sendFile(request, response, fileName, inputStream, contentLength, contentType);
Run Code Online (Sandbox Code Playgroud)
Liferay使用上述方法下载其Message Boardsportlet的附件.您可以在此处查看源代码.我没试过这个,但我想你可以在serveResourceportlet 的方法中编写这段代码,然后提供resourceURL下载或在<img>标签中使用它的URL .
DLAppService如果使用此方法,则DLFileEntry表中将存在此文件的数据库条目,该文件也将显示在Documents & Mediaportlet中.
存储:
添加文件的示例代码:
FileEntry = DLAppServiceUtil.addFileEntry(repositoryId, folderId, sourceFileName, mimeType, title, description, changeLog, bytes, serviceContext);
Run Code Online (Sandbox Code Playgroud)
您可以在这里查看其他方法和课程.
检索:
这是在这个答案中解释的.
ImageLocalService(专门用于图像)对于此方法,您需要将ImageID存储在某处以便以后检索图像.
存储:
以下是在liferay中添加/更新图像的方法:
// to Add an image
long imageID = 0;
imageID = CounterLocalServiceUtil.increment();
ImageLocalServiceUtil.updateImage(imageID, bytes);
// to update the same image, pass the existing Image ID
ImageLocalServiceUtil.updateImage(existingImageID, bytes);
Run Code Online (Sandbox Code Playgroud)
恢复:
您可以在JSP中编写以下代码:
<img alt="My Image"
id="myImgID"
title="This my image stored in liferay"
src="<%=themeDisplay.getPathImage()%>/any_string_will_do_?img_id=<%=myImageId%>&img_timestamp=<%=someTimestampOrRandomString %>" />
Run Code Online (Sandbox Code Playgroud)
注意:
img_timestamp=<%=someTimestampOrRandomString %>",此字符串是可选参数,可以跳过.
这是为了使浏览器每次刷新页面时都从服务器而不是浏览器缓存中检索图像.
希望这可以帮助.