1

Is it possible to obtain size of a file from document library in velocity template?

I have a content structure with repetitive files and a very simple template, like below:

#foreach($f in $file.siblings)
    <a href="$f.getData()">download</a>
#end

The $f.getType(), returns value: document_library.

Thanks!

dotintegral
  • 918
  • 1
  • 10
  • 23

2 Answers2

1

Unfortunately, this information is not directly accessible from the $f variable that was injected in your template by Liferay. For Liferay 6.1, the $f.data holds the url to the document in the following form:

/documents/[group-id]/[folder-id]/[file-name]

Luckily, we can hack our way through this and get hold of the actual file by using the service API, which is accessible in Velocity templates thanks to the $serviceLocator. For this variable to be available, you must enable it in portal-ext.properties by configuring the following property:

#
# Input a comma delimited list of variables which are restricted from the
# context in Velocity based Journal templates.
#
journal.template.velocity.restricted.variables=

Once we have this enabled, we can call the right service to retrieve a FileEntry object based on the parts in the document URL. And then we have the size as well:

#set($url = $f.data)
#set($parts = $stringUtil.split($url, "/"))

#set($group_id = $getterUtil.getLong($parts.get(2)))
#set($folder_id = $getterUtil.getLong($parts.get(3)))
#set($doc_name = $parts.get(4))

#set($docService = $serviceLocator.findService("com.liferay.portlet.documentlibrary.service.DLAppLocalService"))
#set($fileEntry = $docService.getFileEntry($group_id, $folder_id, $doc_name))

The file size is: $fileEntry.size
p.mesotten
  • 1,402
  • 1
  • 14
  • 26
0

That don't work because you have to escape de url try this.

#set($url = $httpUtil.decodeURL($ficheiro.getData(), true))
#set($parts = $stringUtil.split($url, "/"))

#set($group_id = $getterUtil.getLong($parts.get(2)))
#set($folder_id = $getterUtil.getLong($parts.get(3)))
#set($doc_name = $parts.get(4))

#set($docService = $serviceLocator.findService("com.liferay.portlet.documentlibrary.service.DLAppLocalService"))

#set($fileEntry = $docService.getFileEntry($group_id, $folder_id, $doc_name))

The file size is: $fileEntry.size
Marco Mendão
  • 329
  • 2
  • 5