Saturday, July 18, 2015

How to Upload Documents and Files in Liferay


Today we will discuss how to upload documents and files in Liferay. For this we will use Document and Media Portlet of Liferay. We already discuss all method in detail. Here we create a application where user can browse the documents and upload the documents and also able to download the uploaded documents. Before reading this blog it is highly recommended to read my previous blogs on Document and Media Portlet in Detal and  Upload Documents Programatically in Liferay .

So lets start this step by step:-

Step 1:-Create Liferay Project and Portlet
Create a Liferay Project in eclipse and then create a MVC portlet in the Project.For theses you may refer Step 1 and Step 2 of my previous blog Here .





Step 2:-Create Your Form
Open view.jsp and paste this code:-

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
<portlet:defineObjects />
<portlet:actionURL var="uplaodURL" name="uploadDocument"></portlet:actionURL>
<portlet:actionURL var="downloadURL" name="downloadFiles"></portlet:actionURL>
<b>Please Upload a Document</b>
<form action="<%=uplaodURL%>" method="post" enctype="multipart/form-data">
<input type="file" name="uploadedFile">
<input type="Submit" name="Submit">
</form>
<a href="<%=downloadURL%>">Download Files</a>
view raw view.jsp hosted with ❤ by GitHub

Explanation:-


  • Here in form we use enctype="multipart/form-data". If we provide functionality of upload file than we have to change the enctype default value is application/x-www-form-urlencoded. For detail you may visit here.
  • name="uploadedFile" this attribute is used to fetch mimeType, location of file etc. in java code.


Step 3:-Create portlet.properties
Create a property file in src with name portlet.properties and paste this content:-

fileupload.folder.name=File_Upload
fileupload.folder.description=This folder is create for Upload documents


Step 4:-Entry for thumbnails
If file is too large liferay not created thumbnail because default maximum size for thumbnail creation of file is 100MB only.Due to this a error comes as "File is too large for preview or thumbnail generation ".So open portal-ext.properties and paste this line and restart the Server.

dl.file.entry.previewable.processor.max.size=-1 


Step 5:-Create method in Java Class
Open your Java class and Paste this Content:-

package com.document.upload;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.repository.model.FileEntry;
import com.liferay.portal.kernel.repository.model.Folder;
import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.service.ServiceContext;
import com.liferay.portal.service.ServiceContextFactory;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.portal.util.PortalUtil;
import com.liferay.portlet.documentlibrary.model.DLFileEntry;
import com.liferay.portlet.documentlibrary.model.DLFolder;
import com.liferay.portlet.documentlibrary.model.DLFolderConstants;
import com.liferay.portlet.documentlibrary.service.DLAppServiceUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;
import com.liferay.util.portlet.PortletProps;
/**
* Portlet implementation class DocumentUpload
*/
public class DocumentUpload extends MVCPortlet {
private static String ROOT_FOLDER_NAME = PortletProps.get("fileupload.folder.name");
private static String ROOT_FOLDER_DESCRIPTION = PortletProps.get("fileupload.folder.description");
private static long PARENT_FOLDER_ID = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID;
public void uploadDocument(ActionRequest actionRequest,ActionResponse actionResponse) throws IOException,PortletException, PortalException, SystemException
{
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
createFolder(actionRequest, themeDisplay);
fileUpload(themeDisplay, actionRequest);
}
public void downloadFiles(ActionRequest actionRequest,ActionResponse actionResponse) throws IOException,PortletException, PortalException, SystemException
{
ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
Map<String,String> urlMap = getAllFileLink(themeDisplay);
actionRequest.setAttribute("urlMap", urlMap);
actionResponse.setRenderParameter("jspPage","/html/documentupload/download.jsp");
}
public Folder createFolder(ActionRequest actionRequest,ThemeDisplay themeDisplay)
{
boolean folderExist = isFolderExist(themeDisplay);
Folder folder = null;
if (!folderExist) {
long repositoryId = themeDisplay.getScopeGroupId();
try {
ServiceContext serviceContext = ServiceContextFactory.getInstance(DLFolder.class.getName(), actionRequest);
folder = DLAppServiceUtil.addFolder(repositoryId,PARENT_FOLDER_ID, ROOT_FOLDER_NAME,ROOT_FOLDER_DESCRIPTION, serviceContext);
} catch (PortalException e1) {
e1.printStackTrace();
} catch (SystemException e1) {
e1.printStackTrace();
}
}
return folder;
}
public boolean isFolderExist(ThemeDisplay themeDisplay){
boolean folderExist = false;
try {
DLAppServiceUtil.getFolder(themeDisplay.getScopeGroupId(), PARENT_FOLDER_ID, ROOT_FOLDER_NAME);
folderExist = true;
System.out.println("Folder is already Exist");
} catch (Exception e) {
System.out.println(e.getMessage());
}
return folderExist;
}
public Folder getFolder(ThemeDisplay themeDisplay){
Folder folder = null;
try {
folder =DLAppServiceUtil.getFolder(themeDisplay.getScopeGroupId(), PARENT_FOLDER_ID, ROOT_FOLDER_NAME);
} catch (Exception e) {
System.out.println(e.getMessage());
}
return folder;
}
public void fileUpload(ThemeDisplay themeDisplay,ActionRequest actionRequest)
{
UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);
String fileName=uploadPortletRequest.getFileName("uploadedFile");
File file = uploadPortletRequest.getFile("uploadedFile");
String mimeType = uploadPortletRequest.getContentType("uploadedFile");
String title = fileName;
String description = "This file is added via programatically";
long repositoryId = themeDisplay.getScopeGroupId();
System.out.println("Title=>"+title);
try
{
Folder folder = getFolder(themeDisplay);
ServiceContext serviceContext = ServiceContextFactory.getInstance(DLFileEntry.class.getName(), actionRequest);
InputStream is = new FileInputStream( file );
DLAppServiceUtil.addFileEntry(repositoryId, folder.getFolderId(), fileName, mimeType,
title, description, "", is, file.getTotalSpace(), serviceContext);
} catch (Exception e)
{
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public Map<String, String> getAllFileLink(ThemeDisplay themeDisplay){
Map<String, String> urlMap = new HashMap<String, String>();//key = file name ,value = url
long repositoryId = themeDisplay.getScopeGroupId();
try {
Folder folder =getFolder(themeDisplay);
List<FileEntry> fileEntries = DLAppServiceUtil.getFileEntries(repositoryId, folder.getFolderId());
for (FileEntry file : fileEntries) {
String url = themeDisplay.getPortalURL() + themeDisplay.getPathContext() + "/documents/" + themeDisplay.getScopeGroupId() + "/" +
file.getFolderId() + "/" +file.getTitle() ;
urlMap.put(file.getTitle().split("\\.")[0], url);// remove jpg or pdf
}
} catch (Exception e) {
e.printStackTrace();
}
return urlMap;
}
}

Explanation:-


  • Here we fetch all the information related to file by UploadPortletRequest object and passing "uploadedFile" which is same as name attribute in our view.jsp for input type file.
  • All the method used in this class are already explained in my previous blog you can check it Here

Note:-

If your form contain both file and fields like text field than you have to get it by passing "UploadPortletRequest " Object. Ex:-
Like we have a form with file and text box name email. Than

ParamUtil.get(actionRequest,"email") always return null

You must use this:-

ParamUtil.get(uploadPortletRequest ,"email");


Step 6:-Create download.jsp
Create a jsp file download.jsp that contain all the links to uploaded files that belong to a particular folder.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<b>Click link to download files</b>
<br><br>
<c:forEach items="${urlMap}" var="links">
<a href="${links.value}" target="blank">${links.key}</a><br>
</c:forEach>
view raw download.jsp hosted with ❤ by GitHub

Explanation:-

Here we use jstl tags so for using jstl we have to provide entry in liferay-plugin-package.properties as :-

portal-dependency-jars=\
    jstl-api.jar,\
    jstl-impl.jar

Step 7:-Check Output
Now deploy your portlet add to page and Check the output as:-




Project Structure:-





You can Download Source code from How to Upload Documents and Files in Liferay.

Hope this will Help....




No comments:

Post a Comment

Total Pageviews

1042910

Number Of Unique Visitor

Free counters!