Liferay File Upload

Liferay file upload tutorial provides sample code to upload files and how to handle it in MVC Portlet.

Let’s jump into creation of Portlet  to upload a file.

  • view.jsp: view.jsp file contains form that will have file input
    1. <%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
      <%@ taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
      <%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme" %>
      <%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui" %>
      <%@ taglib uri="http://liferay.com/tld/util" prefix="liferay-util" %>
      <%@ taglib uri="http://liferay.com/tld/portlet" prefix="liferay-portlet" %>
      <liferay-theme:defineObjects/>
      <portlet:defineObjects/>
      
      This is the <b>Fileupload</b> portlet.
      
      <portlet:actionURL var="uploadFile" name="uploadFileAction">
      
      </portlet:actionURL>
      <aui:form action="<%=uploadFile %>" method="post" enctype="multipart/form-data">
       <aui:input type="file" name="sampleFile" />
       <button type="submit" class="defaultButton" style="margin-left: 10px;">Upload</button>
      </aui:form>
  • Action Controller:   In the action method,  use the below line of code to get UploadPortletRequest from actionRequest and use uploadPortletRequest.getFile(“{form-input-name}”) to get the File contents Directly
    •      UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest); 
  • UploadPortlet.java file
    1. public class UploadPortlet extends MVCPortlet {
       
       
       public void uploadFileAction(ActionRequest actionRequest,ActionResponse actionResponse){
       
             UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest); 
             ByteArrayFileInputStream inputStream = null;
              try {
                   File file = uploadPortletRequest.getFile("sampleFile");
                   if (!file.exists()) {
                     System.out.println("Empty File");
                  }
                 if ((file != null) && file.exists()) {
                        inputStream = new ByteArrayFileInputStream(file, 1024);
                         byte[] data;
                         try {
                                data = FileUtil.getBytes(inputStream);
                           } catch (IOException e) {
                                   e.printStackTrace();
                            }
                 }
       }
       finally {
       StreamUtil.cleanUp(inputStream);
       }
       }
      
      }

Deploy the portlet and access the portlet on page.

Liferay File Upload

 

Hope this helps!!

Download Liferay File Upload Java  Code Here

 

Leave a Comment

Your email address will not be published. Required fields are marked *