Forums

Home » Liferay Portal » English » 3. Development

Combination View Flat View Tree View
Threads [ Previous | Next ]
toggle
Rakesh Goswami
File upload in specific folder
March 29, 2012 2:39 AM
Answer

Rakesh Goswami

Rank: New Member

Posts: 15

Join Date: February 20, 2012

Recent Posts

I am using liferay 6.0.5. I am uploading file using following code.

1UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
2 String submissionFileName = uploadRequest.getFileName("file");
3    File submissionFile = uploadRequest.getFile("file");


this works fine and upload file in tomcat's temp directory with some different file name. What I want is.."There is one folder docs in my project directory. I want uploaded file in this directory with same name". How to do this in liferay.?
Jitendra Rajput
RE: File upload in specific folder
March 29, 2012 3:06 AM
Answer

Jitendra Rajput

Rank: Liferay Master

Posts: 709

Join Date: January 7, 2011

Recent Posts

i guess thats the manual stuff ..You need to write your own code ..once file is available inside temp folder ..you can rename it to original name ..once it is rename you can store this to any specific folder/document library.
Rakesh Goswami
RE: File upload in specific folder
March 29, 2012 3:24 AM
Answer

Rakesh Goswami

Rank: New Member

Posts: 15

Join Date: February 20, 2012

Recent Posts

I explain full flow. I am creating auto generated doc file with some data from UI input replacing the bookmark in my template file. Then I am putting that file in doc library. Now On my custom portlet I am providing link to view/download doc file that is created. And on that same page one file upload is available. Now what I am trying to do is replace the old doc library file with the uploaded file in doc library. and in tomcat temp directory on every file upload,uploaded document is getting different names..how to identify which one is the last one. Please suggest any alternative way to achieve what I am trying to do..Thank you.
Jitendra Rajput
RE: File upload in specific folder
March 29, 2012 4:04 AM
Answer

Jitendra Rajput

Rank: Liferay Master

Posts: 709

Join Date: January 7, 2011

Recent Posts

you can use below code to rename your uploded fie to original name.
 1
 2UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
 3File  tempFile = uploadRequest.getFile("file");
 4
 5         File destination = null;
 6        String path = tempFile .getPath();
 7        path = path.substring(0, path.lastIndexOf(StringPool.BACK_SLASH) + 1);
 8        String fileNm = uploadRequest.getFileName("file");
 9        if (Validator.isNotNull(fileNm))
10        {
11
12            path = path.concat(fileNm);
13            destination = new File(path);
14            FileUtil.copyFile(tempFile , destination);
15            FileUtil.delete(tempFile );
16        }
Rakesh Goswami
RE: File upload in specific folder
March 29, 2012 4:28 AM
Answer
sheela mk
RE: File upload in specific folder
June 27, 2012 1:41 AM
Answer

sheela mk

Rank: Regular Member

Posts: 112

Join Date: February 16, 2012

Recent Posts

Hai..All..how to use attribute of below for uplaoding file..<aui:form tag...

I dont find this attribute..in aui.tld file...

enctype="multipart/form-data"

emoticon
Manish Yadav
RE: File upload in specific folder
June 27, 2012 11:01 AM
Answer

Manish Yadav

Rank: Expert

Posts: 384

Join Date: May 26, 2012

Recent Posts

in place of alloy UI you can use
<form name="UploadForm" action="<portlet:actionURL/>" enctype="multipart/form-data" method="POST">
<input type="file" name="fileName" size="50"><br>
</form>
sheela mk
RE: File upload in specific folder
June 27, 2012 11:38 PM
Answer

sheela mk

Rank: Regular Member

Posts: 112

Join Date: February 16, 2012

Recent Posts

Hai..My complete..Project is on AUI tags..I cant change..it..for normal HTML tags..Pls Let me know any other Solution...emoticonemoticon

if you find..
Manish Yadav
RE: File upload in specific folder
June 28, 2012 1:53 AM
Answer

Manish Yadav

Rank: Expert

Posts: 384

Join Date: May 26, 2012

Recent Posts

sheela mk:
Hai..My complete..Project is on AUI tags..I cant change..it..for normal HTML tags..Pls Let me know any other Solution...emoticonemoticon

if you find..



then you can use
<aui:form action="<%= editArticleActionURL %>" enctype="multipart/form-data" method="post" name="fm1">
</aui:form>

it will work
sheela mk
RE: File upload in specific folder
June 28, 2012 2:47 AM
Answer

sheela mk

Rank: Regular Member

Posts: 112

Join Date: February 16, 2012

Recent Posts

But its not working..if i put file uploading field with other fields,..other fields values only..will not come..in the list..

On removing..File Upload..List values gets populated..from jsp.
Manish Yadav
RE: File upload in specific folder
June 29, 2012 12:34 PM
Answer

Manish Yadav

Rank: Expert

Posts: 384

Join Date: May 26, 2012

Recent Posts

sheela mk:
But its not working..if i put file uploading field with other fields,..other fields values only..will not come..in the list..

On removing..File Upload..List values gets populated..from jsp.



you can use UploadPortletRequest object for uploading file with other attribute in form

process action method
 1
 2public void requestMeeting(ActionRequest actionRequest,
 3        ActionResponse actionResponse) throws IOException, PortletException, SystemException, PortalException {
 4   
 5
 6    PortletURL portletURL = getPortletURL(actionRequest);
 7   
 8//   
 9    try {   
10       
11        UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
12        ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
13        ServiceContext serviceContext = ServiceContextFactory.getInstance(DLFileEntry.class.getName(), actionRequest);
14       
15       
16        String title = Integer.toString(ParamUtil.getInteger(uploadRequest, "title"));
17        String email = ParamUtil.getString(uploadRequest, "email");
18        String name = ParamUtil.getString(uploadRequest, "name");
19        String sourceFileName = uploadRequest.getFileName("file");
20        File file = uploadRequest.getFile("file");   
21
22
23//then you can wtrite your logic here


jsp you can use normal html or aui whichever you feel comfortable
sheela mk
RE: File upload in specific folder
July 1, 2012 10:31 PM
Answer

sheela mk

Rank: Regular Member

Posts: 112

Join Date: February 16, 2012

Recent Posts

K..Thanks Manish..I got it..

Can you pls let me know about..Ajax in liferay..if you knowing well..using JQuery..and using AUI Api..Which one is better to use..and Why...

If any good link pls let me know..
Manish Yadav
RE: File upload in specific folder
July 2, 2012 12:58 AM
Answer

Manish Yadav

Rank: Expert

Posts: 384

Join Date: May 26, 2012

Recent Posts

sheela mk:


..Ajax in liferay..if you knowing well..using JQuery..and using AUI Api..Which one is better to use..and Why...


I used only Jquery Ajax .I haven't use AUI for ajax.
below is jquery Ajax for submitting form

view.jsp file

 1<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
 2<%@page import="javax.portlet.PortletURL"%>
 3<portlet:resourceURL var="ajaxUrl" />
 4<script>
 5function ajaxcall()
 6{   
 7var  empname= document.SubmitForm.empname.value;
 8var employeeId=document.SubmitForm.employeeId.value;
 9var ajaxdata=name+":"+employeeId;
10
11    jQuery.ajax({
12                type     : "POST",
13                url      : "<%=ajaxUrl%>",
14                data     : "ajaxdata=" +ajaxdata,
15                success  : function(data){
16               
17                //write your logic here
18               
19                }
20                  
21                },
22                async    :    false,
23                });
24
25   
26}
27
28<form name="SubmitForm" id="SubmitForm" action='#' method="post"  >
29<input type="text" size="30" id="empname" name="empname">
30<input type="text" size="30" id="employeeId" name="employeeId">
31<button type="button" id="submitButton" onclick="ajaxcall()" >Submit Form</button>
32</form>


JavaActtionClass

 1
 2public void serveResource(ResourceRequest resourceRequest, ResourceResponse res) throws PortletException, IOException {
 3            final String METHOD_NAME="serveResource";
 4            String userString=resourceRequest.getParameter("ajaxdata");
 5      
 6            PrintWriter out = res.getWriter();
 7            
 8            
 9             if(null!=userString&&!userString.isEmpty())
10            {
11                    String [] str= userString.split(":");
12                    String empname=str[0];
13                    String employeelID=str[1];
14                                       
15                                        int status= SubmitRecoredInDB(empname,employeelID)
16                    //write your logic here for returning values you can use
17                  
18                    you can use out.print()
19                                        if(status==1)
20                    out.print("your message successfully submited");
21                                        else
22                                          out.print("execption occurs while submitting record in Database");
23                  
24                    } catch (SystemException e) {
25                        
26                        e.printStackTrace();
27                    }
28            }
29            out.flush();
30            out.close();
31        }





if you want AUI then only jsp you need to change ...serveResource method will same for both AUI and Jquery
Laura Liparulo
RE: File upload in specific folder
July 6, 2012 10:49 AM
Answer

Laura Liparulo

Rank: Junior Member

Posts: 38

Join Date: June 30, 2012

Recent Posts

Hi! I'm posting you a full working example emoticon

You can specify the upload folder in the portlet.xml

1    <init-param>
2            <name>uploadFolder</name>
3            <value>/home/laura/uploads/</value>
4        </init-param>


The File is uploaded to the folder identified by the "uploadFolder" portlet initialization parameter.

view.jsp:

 1
 2
 3<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
 4<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui" %>
 5<%@ page import="javax.portlet.PortletPreferences" %>
 6<portlet:defineObjects />
 7
 8You can upload a new clinical case clicking on "Upload case".
 9<br />
10
11<portlet:renderURL var="editCaseURL">
12<portlet:param name="jspPage" value="/edit.jsp" />
13</portlet:renderURL>
14
15<aui:button onClick="<%=editCaseURL%>" value="Upload case" />


edit.jsp:

 1<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>
 2<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui"%>
 3<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui"%>
 4<%@ page import="com.liferay.portal.kernel.util.ParamUtil"%>
 5<%@ page import="com.liferay.portal.kernel.util.Validator"%>
 6<%@ page import="javax.portlet.PortletPreferences"%>
 7
 8<portlet:defineObjects />
 9<%  //... %>
10<liferay-ui:success key="success" message=" YEAH. Case uploaded successfully!" />
11<liferay-ui:error key="error"
12    message="Sorry, an error prevented the upload. Please try again." />
13
14<portlet:actionURL var="editCaseURL" name="uploadCase">
15    <portlet:param name="jspPage" value="/edit.jsp" />
16</portlet:actionURL>
17
18<aui:form action="<%= editCaseURL %>" enctype="multipart/form-data" method="post" >
19<aui:input type="file" name="fileName" size="75"/>
20
21
22<aui:button type="submit" value="Save" />
23</aui:form>



And this is the portlet class :

 1package it.laura.test;
 2
 3import java.io.FileInputStream;
 4import java.io.FileNotFoundException;
 5import java.io.FileOutputStream;
 6import java.io.IOException;
 7
 8import javax.portlet.ActionRequest;
 9import javax.portlet.ActionResponse;
10import javax.portlet.PortletContext;
11
12
13import javax.portlet.PortletException;
14import javax.portlet.PortletPreferences;
15
16
17import com.liferay.portal.kernel.log.LogFactoryUtil;
18import com.liferay.portal.kernel.servlet.SessionErrors;
19import com.liferay.portal.kernel.servlet.SessionMessages;
20import com.liferay.portal.kernel.upload.UploadPortletRequest;
21import com.liferay.portal.kernel.util.FileUtil;
22
23import java.io.File;
24import com.liferay.portal.util.PortalUtil;
25import com.liferay.util.bridges.mvc.MVCPortlet;
26
27
28import org.apache.commons.logging.Log;
29import org.apache.commons.logging.LogFactory;
30
31
32public class UploadCase extends MVCPortlet {
33
34
35    protected String realPath=null;
36    private static Log logger = LogFactory.getLog(UploadCase.class);
37
38    public void uploadCase(ActionRequest actionRequest, ActionResponse actionRresponse) throws PortletException, IOException
39    { 
40        String folder=getInitParameter("uploadFolder");
41        realPath = getPortletContext().getRealPath("/");
42        byte[] bytes = null;
43        PortletContext portletContext = actionRequest.getPortletSession().getPortletContext();
44        logger.info("RealPath"+realPath+" UploadFolder :"+folder);
45        try{
46            logger.info(" Into the Try");
47            UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
48
49             String sourceFileName =uploadRequest.getFileName("fileName");
50       
51    File file = uploadRequest.getFile("fileName");
52
53            try {      
54                bytes = FileUtil.getBytes(file);
55            } catch (IOException e2) {            
56                e2.printStackTrace();
57            }
58            File newFile=null;
59            
60            if ((bytes != null) && (bytes.length > 0)) {
61            
62            try {
63            newFile = new File(folder+sourceFileName);
64            FileInputStream fileInputStream = new FileInputStream(file);
65            FileOutputStream fileOutputStream = new FileOutputStream(newFile);            
66            fileInputStream.read(bytes);               
67            fileOutputStream.write(bytes, 0, bytes.length);                   
68            fileOutputStream.close();
69            fileInputStream.close();
70            SessionMessages.add(actionRequest, "success");
71        }
72            catch (FileNotFoundException e) {
73                System.out.println("File Not Found.");               
74                e.printStackTrace();
75                SessionMessages.add(actionRequest, "error");
76            }
77            catch (IOException e1){
78                System.out.println("Error Reading The File.");
79                e1.printStackTrace();
80                SessionMessages.add(actionRequest, "error");
81            }
82        }
83            
84} catch (Exception e) {
85        System.out.println("Exception::::"+e.getMessage());
86        SessionMessages.add(actionRequest, "error");
87    }
88}
89


Enjoy it! :-)