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...

Liferay Custom Field and Custom Attribute (Using Liferay UI and Programatically)

Custom fields are a way to add attributes to many types of assets in the portal. Its basically help us to add additional fields to existed models or entities. Adding some more additional attributes to existed entities or models helps us so to meet our requirements. Liferay provide two way's to allow the creation of Custom Fields. 1. Using Liferay UI 2. Programatically Lets look these both topic one by one-: Suppose you have a scenario where its needed to add few fields in your User_ Table So its simple to add using Liferay UI just you need to follow these steps-: 1. Using Liferay UI-:   Goto-> Control-Panel -> Click on Custom Field A List will be displayed-: Now you can add your custom fields for any entity in the list. Click on User Entity and a page will be displayed like this-: Now add these value in respective fields-: KEY- myContactId Type- Select Integer After adding the custom field we can view, update from the Lifera...