Skip to main content

Upload File and maintain folder structure for specific category wise files in Liferay 6.2

Step 1-: Create a portlet - FileUpload-Portlet

Step 2-: Create init.jsp and add these line-:

<%@ 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/ui" prefix="liferay-ui"%>
<%@ page import="com.liferay.portal.kernel.util.ParamUtil"%>
<%@ page import="com.liferay.portal.kernel.util.Validator"%>
<%@ page import="javax.portlet.PortletPreferences"%>
<%@ page import="com.liferay.util.PwdGenerator"%>

Step 3-: On view.jsp add these lines

<%@ include file="/html/fileuploadprog/init.jsp" %>
<portlet:actionURL var="redirectUploadURL" name="redirectUpload"></portlet:actionURL>

<aui:form action="<%= redirectUploadURL %>">
  <aui:button name="UploadFile" value="UploadFile" onClick="<%= redirectUploadURL %>"/>
</aui:form>

Step 4-: Create a jsp page uploadFile.jsp and add these lines

<%@ include file="/html/fileuploadprog/init.jsp" %>


<portlet:actionURL var="editCaseURL" name="uploadCase"/>

<liferay-ui:success key="success" message=" File !!! uploaded successfully!" />
<liferay-ui:error key="error" message="Sorry, an error occur while uploading file. Please try again." />


<aui:form action="<%=editCaseURL%>" enctype="multipart/form-data" method="post">
 
        <aui:select name="folderStructure" id="folderStructure" onChange="console.log(this.value)">
             <aui:option value="store">Store</aui:option>
             <aui:option value="floor">Floor</aui:option>
             <aui:option value="dept">Department</aui:option>
       </aui:select>
<aui:input type="file" name="fileName" size="75" />
<aui:button type="submit" value="Upload"/>

</aui:form>

Step 5-: In the controller class add these lines

private static Log log = LogFactoryUtil.getLog(FileUploadProg.class);

//This is doView helps in rendering the page
public void doView(RenderRequest renderRequest,RenderResponse renderResponse)throws IOException,PortletException{

log.info("--Inside DoView----");

ThemeDisplay themeDisplay = (ThemeDisplay) renderRequest.getAttribute(WebKeys.THEME_DISPLAY);
PortletRequestDispatcher dispatcher = null;
PortletSession session = renderRequest.getPortletSession();

String portletTitle = renderRequest.getParameter("custom_portlet");
log.info("FileUploadPortlet.doView renderRequest.getParameter="+portletTitle);

if(portletTitle != null && portletTitle.equalsIgnoreCase("redirectUpload")){
dispatcher = getPortletContext().getRequestDispatcher("/html/fileuploadprog/uploadFile.jsp");
dispatcher.forward(renderRequest, renderResponse);
}else if(portletTitle != null && portletTitle.equalsIgnoreCase("success")){
dispatcher = getPortletContext().getRequestDispatcher("/html/fileuploadprog/view.jsp");
dispatcher.forward(renderRequest, renderResponse);
}
super.doView(renderRequest, renderResponse);
}

//Custom action class
       //This method gets executed once we click button on view.jsp page
public void redirectUpload(ActionRequest actionRequest,ActionResponse actionResponse){
actionResponse.setRenderParameter("custom_portlet", "redirectUpload");
}

//This method get executed when we click on upload on fileUpload.jsp
public void uploadCase(ActionRequest actionRequest,ActionResponse actionResponse) throws PortletException,IOException {

UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
//This gets value from init param written in portlet.xml
String someFolder = getInitParameter("uploadFolder");
String myNewFolder= uploadRequest.getParameter("folderStructure");
String folder = someFolder+myNewFolder;
try {      
       if (uploadRequest.getSize("fileName")==0) {
            SessionErrors.add(actionRequest, "error");
            }

       String sourceFileName = uploadRequest.getFileName("fileName");
       File file = uploadRequest.getFile("fileName");

       log.info("Name of file:" + uploadRequest.getFileName("fileName"));
       File newFolder = null;
       newFolder = new File(folder);
   if(!newFolder.exists()){
           newFolder.mkdir();
          }
       File newfile = null;
       newfile = new File(folder+"/"+sourceFileName+"-"+myNewFolder);
       log.info("New file name: " + newfile.getName());
       log.info("New file path: " + newfile.getPath());

       InputStream in = new BufferedInputStream(uploadRequest.getFileAsStream("fileName"));
       FileInputStream fis = new FileInputStream(file);
       FileOutputStream fos = new FileOutputStream(newfile);

       byte[] bytes_ = FileUtil.getBytes(in);
       int i = fis.read(bytes_);

       while (i != -1) {
        fos.write(bytes_, 0, i);
        i = fis.read(bytes_);
       }
       fis.close();
       fos.close();
       Float size = (float) newfile.length();
       log.info("file size bytes:" + size);
       log.info("file size Mb:" + size / 1048576);

       log.info("File created: " + newfile.getName());
       SessionMessages.add(actionRequest, "success");
                actionResponse.setRenderParameter("custom_portlet", "success");
} catch (FileNotFoundException e) {
log.info("File Not Found.");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
} catch (NullPointerException e) {
log.info("File Not Found");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}catch (IOException e1) {
log.info("Error Reading The File.");
SessionMessages.add(actionRequest, "error");
e1.printStackTrace();
}

}


Step 6-: Open portlet.xml and update these line under init param tag

<init-param>
   <name>uploadFolder</name>
   <value>/home/FolderOne/FolderTwo/</value>
</init-param>








Comments

Popular posts from this blog

Liferay 7.1 Topics Coming Soon stay connected

1. Liferay 7.1 Service Builder 2. Rest Service and Liferay 3. Consuming SOAP service with Liferay 7.1 4. Creating Theme With Liferay 7.1 Using Liferay IDE Using NPM 5. Create Angular NPM Module 6. Web Content Management 7. OSGI Basic 8. Liferay 7.1 with more than 1 DB 9. A sample project 10. Liferay Dev Ops

How the portal page is loaded with respective portlets

How the portal page is loaded with respective portlets When a user requests a page with a URL, 1.    The browser sends the request to the Application Server (AS). 2.    Liferay gets the page name from the URL. 3.    It goes to the layout database table and finds the related        theme and page layout. 4.    Based on the page layout, Liferay finds the portlets added        into each area of the page layout. 5.    Liferay runs the portlet and adds the output in the        portlet.vm template. 6.    Liferay interprets the portlet.vm template and adds the output        in the page layout. 7.    Then Liferay interprets the page layout and adds the output in        the portal_normal.vm template. 8.    After that Liferay interprets the portal...

Service Builder 1

Service Builder uses the spring and hibernate integration Data Access Objects implementation mechanism in short we can call it as DAO implementation. Here Service Builder Tool will use the spring and hibernate technology to develop service layer to Plugin portlet. Service Layer's -: Persistence/DAO classes: Persistence or DAO classes will provide the direct data base interaction like insert, delete and update the data in table. such kind of logic will be present in this classes. Conceptually for each table we have one persistence class that will interact with table. Here actual data base interaction code will be present. As we know that to interact with database we need hibernate/jdbc in java. Persistence/DAO classes we will get the session factory object and from that we will open session, with that session object we will do all database interactions, once we finish all tasks we will close the session. Model/POJO -: The model or POJO classes wi...