Fórum

File upload in specific folder

Rakesh Goswami, modificado 12 Anos atrás.

File upload in specific folder

New Member Postagens: 15 Data de Entrada: 21/02/12 Postagens Recentes
I am using liferay 6.0.5. I am uploading file using following code.

UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
 String submissionFileName = uploadRequest.getFileName("file");
    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.?
thumbnail
Jitendra Rajput, modificado 12 Anos atrás.

RE: File upload in specific folder

Liferay Master Postagens: 875 Data de Entrada: 07/01/11 Postagens Recentes
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, modificado 12 Anos atrás.

RE: File upload in specific folder

New Member Postagens: 15 Data de Entrada: 21/02/12 Postagens Recentes
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.
thumbnail
Jitendra Rajput, modificado 12 Anos atrás.

RE: File upload in specific folder

Liferay Master Postagens: 875 Data de Entrada: 07/01/11 Postagens Recentes
you can use below code to rename your uploded fie to original name.

UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
File  tempFile = uploadRequest.getFile("file");

         File destination = null;
        String path = tempFile .getPath();
        path = path.substring(0, path.lastIndexOf(StringPool.BACK_SLASH) + 1);
        String fileNm = uploadRequest.getFileName("file");
        if (Validator.isNotNull(fileNm))
        {

            path = path.concat(fileNm);
            destination = new File(path);
            FileUtil.copyFile(tempFile , destination);
            FileUtil.delete(tempFile );
        }
thumbnail
sheela mk, modificado 11 Anos atrás.

RE: File upload in specific folder

Regular Member Postagens: 111 Data de Entrada: 17/02/12 Postagens Recentes
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
thumbnail
Manish Yadav, modificado 11 Anos atrás.

RE: File upload in specific folder

Expert Postagens: 493 Data de Entrada: 26/05/12 Postagens Recentes
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>
thumbnail
sheela mk, modificado 11 Anos atrás.

RE: File upload in specific folder

Regular Member Postagens: 111 Data de Entrada: 17/02/12 Postagens Recentes
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..
thumbnail
Manish Yadav, modificado 11 Anos atrás.

RE: File upload in specific folder

Expert Postagens: 493 Data de Entrada: 26/05/12 Postagens Recentes
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
thumbnail
sheela mk, modificado 11 Anos atrás.

RE: File upload in specific folder

Regular Member Postagens: 111 Data de Entrada: 17/02/12 Postagens Recentes
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.
thumbnail
Manish Yadav, modificado 11 Anos atrás.

RE: File upload in specific folder

Expert Postagens: 493 Data de Entrada: 26/05/12 Postagens Recentes
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

public void requestMeeting(ActionRequest actionRequest,
		ActionResponse actionResponse) throws IOException, PortletException, SystemException, PortalException {
	

	PortletURL portletURL = getPortletURL(actionRequest);
	
//	
	try {	
		
		UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);
		ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);
		ServiceContext serviceContext = ServiceContextFactory.getInstance(DLFileEntry.class.getName(), actionRequest);
		
		
		String title = Integer.toString(ParamUtil.getInteger(uploadRequest, "title"));
		String email = ParamUtil.getString(uploadRequest, "email");
		String name = ParamUtil.getString(uploadRequest, "name");
		String sourceFileName = uploadRequest.getFileName("file");
		File file = uploadRequest.getFile("file");	


//then you can wtrite your logic here


jsp you can use normal html or aui whichever you feel comfortable
thumbnail
sheela mk, modificado 11 Anos atrás.

RE: File upload in specific folder

Regular Member Postagens: 111 Data de Entrada: 17/02/12 Postagens Recentes
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..
thumbnail
Manish Yadav, modificado 11 Anos atrás.

RE: File upload in specific folder

Expert Postagens: 493 Data de Entrada: 26/05/12 Postagens Recentes
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

&lt;%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %&gt;
&lt;%@page import="javax.portlet.PortletURL"%&gt;
<portlet:resourceurl var="ajaxUrl" />
<script>
function ajaxcall()
{   
var  empname= document.SubmitForm.empname.value;
var employeeId=document.SubmitForm.employeeId.value;
var ajaxdata=name+":"+employeeId;

    jQuery.ajax({
                type     : "POST",
                url      : "<%=ajaxUrl%>",
                data     : "ajaxdata=" +ajaxdata,
                success  : function(data){
               
                //write your logic here
               
                }
                   
                },
                async    :    false,
                });

   
}

<form name="SubmitForm" id="SubmitForm" action='#' method="post"  >
<input type="text" size="30" id="empname" name="empname">
<input type="text" size="30" id="employeeId" name="employeeId">
<button type="button" id="submitButton" onclick="ajaxcall()" >Submit Form</button>
</form></code></pre><br /><br /><strong>JavaActtionClass</strong><br /><br /><pre><code>
public void serveResource(ResourceRequest resourceRequest, ResourceResponse res) throws PortletException, IOException {
            final String METHOD_NAME="serveResource";
            String userString=resourceRequest.getParameter("ajaxdata");
       
            PrintWriter out = res.getWriter();
            
            
             if(null!=userString&&!userString.isEmpty())
            {
                    String [] str= userString.split(":");
                    String empname=str[0];
                    String employeelID=str[1];
                                        
                                        int status= SubmitRecoredInDB(empname,employeelID)
                    //write your logic here for returning values you can use
                   
                    you can use out.print()
                                        if(status==1)
                    out.print("your message successfully submited");
                                        else
                                          out.print("execption occurs while submitting record in Database");
                   
                    } catch (SystemException e) {
                        
                        e.printStackTrace();
                    }
            }
            out.flush();
            out.close();
        }
</code></pre><br /><br /><br /><br /><br />if you want AUI then only jsp you need to change ...serveResource     method will same for both AUI and Jquery</script>
thumbnail
Laura Liparulo, modificado 11 Anos atrás.

RE: File upload in specific folder

Junior Member Postagens: 38 Data de Entrada: 30/06/12 Postagens Recentes
Hi! I'm posting you a full working example emoticon

You can specify the upload folder in the portlet.xml

	<init-param>
			<name>uploadFolder</name>
			<value>/home/laura/uploads/</value>
		</init-param>


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

view.jsp:



&lt;%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %&gt;
&lt;%@ taglib uri="http://liferay.com/tld/aui" prefix="aui" %&gt;
&lt;%@ page import="javax.portlet.PortletPreferences" %&gt;
<portlet:defineobjects />

You can upload a new clinical case clicking on "Upload case". 
<br>

<portlet:renderurl var="editCaseURL">
<portlet:param name="jspPage" value="/edit.jsp" />
</portlet:renderurl>

<aui:button onClick="<%=editCaseURL%>" value="Upload case" />


edit.jsp:

&lt;%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%&gt;
&lt;%@ taglib uri="http://liferay.com/tld/aui" prefix="aui"%&gt;
&lt;%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui"%&gt;
&lt;%@ page import="com.liferay.portal.kernel.util.ParamUtil"%&gt;
&lt;%@ page import="com.liferay.portal.kernel.util.Validator"%&gt;
&lt;%@ page import="javax.portlet.PortletPreferences"%&gt;

<portlet:defineobjects />
&lt;%  //... %&gt;
<liferay-ui:success key="success" message=" YEAH. Case uploaded successfully!" />
<liferay-ui:error key="error" message="Sorry, an error prevented the upload. Please try again." />

<portlet:actionurl var="editCaseURL" name="uploadCase">
	<portlet:param name="jspPage" value="/edit.jsp" />
</portlet:actionurl>

<aui:form action="<%= editCaseURL %>" enctype="multipart/form-data" method="post">
<aui:input type="file" name="fileName" size="75" />


<aui:button type="submit" value="Save" />
</aui:form>



And this is the portlet class :

package it.laura.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletContext;


import javax.portlet.PortletException;
import javax.portlet.PortletPreferences;


import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.kernel.util.FileUtil;

import java.io.File;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;


public class UploadCase extends MVCPortlet {


	protected String realPath=null;
	private static Log logger = LogFactory.getLog(UploadCase.class);

	public void uploadCase(ActionRequest actionRequest, ActionResponse actionRresponse) throws PortletException, IOException
	{  
		String folder=getInitParameter("uploadFolder");
		realPath = getPortletContext().getRealPath("/");
		byte[] bytes = null;
		PortletContext portletContext = actionRequest.getPortletSession().getPortletContext();
		logger.info("RealPath"+realPath+" UploadFolder :"+folder);
		try{ 
			logger.info(" Into the Try");
		    UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(actionRequest);

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

			try {   	
				bytes = FileUtil.getBytes(file);
			} catch (IOException e2) {			
				e2.printStackTrace();
			}
			File newFile=null;
			
			if ((bytes != null) &amp;&amp; (bytes.length &gt; 0)) {
			
			try {
			newFile = new File(folder+sourceFileName);
			FileInputStream fileInputStream = new FileInputStream(file);
			FileOutputStream fileOutputStream = new FileOutputStream(newFile);			
			fileInputStream.read(bytes);				
			fileOutputStream.write(bytes, 0, bytes.length);					
			fileOutputStream.close();
			fileInputStream.close();
			SessionMessages.add(actionRequest, "success");
		} 
			catch (FileNotFoundException e) {
				System.out.println("File Not Found.");				
				e.printStackTrace();
				SessionMessages.add(actionRequest, "error");
			}
			catch (IOException e1){
				System.out.println("Error Reading The File.");
				e1.printStackTrace();
				SessionMessages.add(actionRequest, "error");
			}
		}
	        
} catch (Exception e) {
		System.out.println("Exception::::"+e.getMessage());
		SessionMessages.add(actionRequest, "error");
	}
}
 


Enjoy it! :-)