Fórum

Upload a file and store in server

Rad One, modificado 12 Anos atrás.

Upload a file and store in server

New Member Mensagem: 1 Data de Entrada: 21/04/11 Postagens Recentes
Hello

I want to upload and store a file in local tomcat server file server (something like CKEditor).

So I've created a portlet.
These are my important files:

MyUploadFilePortlet.java:
package com.mine.portlets;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.util.PortalUtil;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletException;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import java.io.File;
import java.io.IOException;

/**
 * Portlet implementation class MyUploadFilePortlet
 */
public class MyUploadFilePortlet extends GenericPortlet {
 
	protected String editJSP;
	protected String viewJSP;

	private static Log _log = LogFactoryUtil.getLog(MyUploadFilePortlet.class);

	public void init() {
		editJSP = getInitParameter("edit-jsp");
		viewJSP = getInitParameter("view-jsp");
    }

	public void processAction(
    	ActionRequest actionRequest, ActionResponse actionResponse)
		throws IOException, PortletException {

		String description = actionRequest.getParameter("description");

		UploadPortletRequest lUploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);

		if (lUploadPortletRequest.getFileName("file") != null && !"".equals(lUploadPortletRequest.getFileName("file"))) {
			File file = lUploadPortletRequest.getFile("file");
			String fileName = lUploadPortletRequest.getFileName("file");
			file.setLastModified(System.currentTimeMillis());
			String fileAbsPath = file.getAbsolutePath();

			PortletPreferences prefs = actionRequest.getPreferences();

			prefs.setValue("VIDEODESCRIPTION", description);
			prefs.setValue("VIDEOURL", fileAbsPath);
			prefs.store();

			System.out.println("VIDEODESCRIPTION=" + description + " path=" + fileAbsPath + " file name=" + fileName);
		}
	}
        
	public void doEdit(
		RenderRequest renderRequest, RenderResponse renderResponse)
		throws IOException, PortletException {

		include(editJSP, renderRequest, renderResponse);
	}
        
	public void doView(
		RenderRequest renderRequest, RenderResponse renderResponse)
		throws IOException, PortletException {

		PortletPreferences prefs = renderRequest.getPreferences();

		String defaultValue = "";

		String description = (String) prefs.getValue("VIDEODESCRIPTION", defaultValue);
		String fileAbsPath = (String) prefs.getValue("VIDEOURL", defaultValue);

		renderRequest.setAttribute("ATTRIBUTE_VIDEODESCRIPTION", description);
		renderRequest.setAttribute("ATTRIBUTE_VIDEOURL", fileAbsPath);

		include(viewJSP, renderRequest, renderResponse);
	}

    protected void include(
    	String path, RenderRequest renderRequest,
    	RenderResponse renderResponse)
		throws IOException, PortletException {

        PortletRequestDispatcher portletRequestDispatcher = getPortletContext().getRequestDispatcher(path);

        if (portletRequestDispatcher == null) {
            _log.error(path + " is not a valid include");
        }
        else {
            portletRequestDispatcher.include(renderRequest, renderResponse);
        }
    }
}

view.jsp
<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>

<portlet:defineobjects />

&lt;%
String description = (String)request.getAttribute("ATTRIBUTE_VIDEODESCRIPTION");
String fileAbsPath = (String)request.getAttribute("ATTRIBUTE_VIDEOURL");
%&gt;

<h3>View mode</h3>
<p>video description: &lt;%= description %&gt;</p>
<p>video path: &lt;%= fileAbsPath %&gt;</p>

edit.jsp
&lt;%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %&gt;

<portlet:defineobjects />

<h3>Edit mode</h3>
<form action="<portlet:actionURL />" method="POST" name="<portlet:namespace />fm" enctype="multipart/form-data">
	<input type="text" name="<portlet:namespace />description"><br>
	<input type="file" name="<portlet:namespace />file"><br>
	<input type="submit">
</form>


So what I want to do exactly is play a video file in view mode.

But my first step is to store uploaded file in local server file system. The form for doing that is en edit mode. So far, in view mode I can get absolute path of the file, file name etc...

How to store an uploaded file ?

I've search through the forum but answers found did not work for me. I've tried DiskFileItemFactory class but I'm missing a lot of things.

Please help.
thumbnail
Suraj Bihari, modificado 12 Anos atrás.

RE: Upload a file and store in server

Junior Member Postagens: 41 Data de Entrada: 20/05/11 Postagens Recentes
Hi Rad,

To upload a file and store it on the server see the following snippet:

UploadPortlet.java

public class UploadPortlet extends GenericPortlet{

	protected String viewJSP;
	protected String process;
	protected Vector<!--?--> v=null;
	protected String realPath=null;

	public void init() throws PortletException {

		viewJSP = getInitParameter("view-jsp");
	}

	public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException
	{  

		realPath = getPortletContext().getRealPath("/");
		System.out.println(realPath);

		byte[] bytes = null;
		PortletContext portletContext = request.getPortletSession().getPortletContext();
		try{ 

			UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request);
			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 {

					System.out.println(sourceFileName);

					newFile = new File(realPath+"html/uploads/"+sourceFileName);
					FileInputStream fileInputStream = new FileInputStream(file);
					FileOutputStream fileOutputStream = new FileOutputStream(newFile);			
					fileInputStream.read(bytes);		
					
					String value = new String(bytes);
					System.out.println(value);
					
					fileOutputStream.write(bytes, 0, bytes.length);					
					fileOutputStream.close();
					fileInputStream.close();
				} 
				catch (FileNotFoundException e) {
					System.out.println("File Not Found.");				
					e.printStackTrace();
				}
				catch (IOException e1){
					System.out.println("Error Reading The File.");
					e1.printStackTrace();
				}
			}

		} catch (Exception e) {
			System.out.println("Exception::::"+e.getMessage());
		}
	}
	public void render(RenderRequest request, RenderResponse response) throws PortletException, IOException
	{

		doView(request,response);
	}

	public void doView(RenderRequest request, RenderResponse response)throws IOException 
	{
		String path=viewJSP;
		PortletRequestDispatcher portletRequestDispatcher = getPortletContext().getRequestDispatcher(path);
		if (portletRequestDispatcher == null) {
			_log.error(viewJSP + " is not a valid include");
		}
		else{

			try{
				portletRequestDispatcher.include(request, response);
			}
			catch(Exception e){				
				_log.error("Error Occured:"+e);
			}
		}
	}
	private static Log _log = LogFactoryUtil.getLog(UploadPortlet2.class);

}


This will save in the upload directory (html/uploads) make sure to create this directory in your portlet.
BTW. If you're creative with ../../.. you can store it outside of the portlet, or dynamically create folders ;-)

View.jsp

&lt;%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %&gt;
&lt;%@ page language="java" contentType="text/html; charset=Windows-1256" pageEncoding="Windows-1256"%&gt;
<portlet:defineobjects />
	<script type="text/javascript">
		function send()
		{
			document.UploadForm.submit();
        }
	</script>
		<h3>Upload portlet:</h3>
		
		<form name="UploadForm" action="<portlet:actionURL/>" enctype="multipart/form-data" method="POST">
		  <input type="file" name="fileName" size="50"><br>
		  <input type="Submit" value="Upload File" onClick="send()">
		</form>



Good luck!
Nhat Le, modificado 12 Anos atrás.

RE: Upload a file and store in server

Junior Member Postagens: 25 Data de Entrada: 05/03/12 Postagens Recentes
Suraj Bihari:
Hi Rad,

To upload a file and store it on the server see the following snippet:

UploadPortlet.java

public class UploadPortlet extends GenericPortlet{

	protected String viewJSP;
	protected String process;
	protected Vector<!--?--> v=null;
	protected String realPath=null;

	public void init() throws PortletException {

		viewJSP = getInitParameter("view-jsp");
	}

	public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException
	{  

		realPath = getPortletContext().getRealPath("/");
		System.out.println(realPath);

		byte[] bytes = null;
		PortletContext portletContext = request.getPortletSession().getPortletContext();
		try{ 

			UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request);
			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 {

					System.out.println(sourceFileName);

					newFile = new File(realPath+"html/uploads/"+sourceFileName);
					FileInputStream fileInputStream = new FileInputStream(file);
					FileOutputStream fileOutputStream = new FileOutputStream(newFile);			
					fileInputStream.read(bytes);		
					
					String value = new String(bytes);
					System.out.println(value);
					
					fileOutputStream.write(bytes, 0, bytes.length);					
					fileOutputStream.close();
					fileInputStream.close();
				} 
				catch (FileNotFoundException e) {
					System.out.println("File Not Found.");				
					e.printStackTrace();
				}
				catch (IOException e1){
					System.out.println("Error Reading The File.");
					e1.printStackTrace();
				}
			}

		} catch (Exception e) {
			System.out.println("Exception::::"+e.getMessage());
		}
	}
	public void render(RenderRequest request, RenderResponse response) throws PortletException, IOException
	{

		doView(request,response);
	}

	public void doView(RenderRequest request, RenderResponse response)throws IOException 
	{
		String path=viewJSP;
		PortletRequestDispatcher portletRequestDispatcher = getPortletContext().getRequestDispatcher(path);
		if (portletRequestDispatcher == null) {
			_log.error(viewJSP + " is not a valid include");
		}
		else{

			try{
				portletRequestDispatcher.include(request, response);
			}
			catch(Exception e){				
				_log.error("Error Occured:"+e);
			}
		}
	}
	private static Log _log = LogFactoryUtil.getLog(UploadPortlet2.class);

}


This will save in the upload directory (html/uploads) make sure to create this directory in your portlet.
BTW. If you're creative with ../../.. you can store it outside of the portlet, or dynamically create folders ;-)

View.jsp

&lt;%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %&gt;
&lt;%@ page language="java" contentType="text/html; charset=Windows-1256" pageEncoding="Windows-1256"%&gt;
<portlet:defineobjects />
	<script type="text/javascript">
		function send()
		{
			document.UploadForm.submit();
        }
	</script>
		<h3>Upload portlet:</h3>
		
		<form name="UploadForm" action="<portlet:actionURL/>" enctype="multipart/form-data" method="POST">
		  <input type="file" name="fileName" size="50"><br>
		  <input type="Submit" value="Upload File" onClick="send()">
		</form>



Good luck!



Hey

Thanks for this, but I was wondering if there is anyway you can send me the full source code of the portlet, as I am trying to use this, but i don't know how to make the view.jsp access the .java file automatically.
Nguyen Le, modificado 11 Anos atrás.

RE: Upload a file and store in server

New Member Postagens: 11 Data de Entrada: 24/04/12 Postagens Recentes
I have 2 components in view.jsp. It's file input tag(html file chooser) and textfield input tag. I want send data in 2 components to JAVA file, save file on web server and insert data received from textfileld into database. I any do 1 in 2 jobs above. Please help to do both.
thumbnail
Manish Kumar Jaiswal, modificado 11 Anos atrás.

RE: Upload a file and store in server

Regular Member Postagens: 153 Data de Entrada: 25/11/08 Postagens Recentes
Nguyen ,

I know its too late for your answer but for the ppl facing this type of problem just let me give the concept to deal with the problem . if you have normal HTML element + File Upload element in the form so when you submit the form it goes to Action and you get ActionRequest now to get the Normal HTML element you can use
actionRequest .getparameter("officephone") or ParamUtil.getString(uploadPortRequst, "officephone") and after getting all the request parameters just convert ActionRequest to UploadPortletRequest like this

UploadPortletRequest uploadPortletRequest = PortalUtil .getUploadPortletRequest(actionRequest);

and now you can get your uploaded file like this

inputStream = uploadPortletRequest.getFileAsStream("fileName");


Regards
Manish
Chandra Rastogi, modificado 11 Anos atrás.

RE: Upload a file and store in server

New Member Postagens: 7 Data de Entrada: 27/12/12 Postagens Recentes
your code is working fine but i have 2 issues
1- My uploaded files are not coming in realPath+"html/uploads/ folder.
2- Where can i view the file that i am uploading? In tomcat/data/dl there are many files with numeric name. how to find out my uploaded file?

Thanks
thumbnail
Akash Jaisawal, modificado 8 Anos atrás.

RE: Upload a file and store in server

Regular Member Postagens: 141 Data de Entrada: 03/03/12 Postagens Recentes
Any one have answer for this, why my uploaded files are coming into the /temp/myportlet folder, how can i upload it in my given path.
thumbnail
Juan Gonzalez P, modificado 12 Anos atrás.

RE: Upload a file and store in server

Liferay Legend Postagens: 3089 Data de Entrada: 28/10/08 Postagens Recentes
Rad One:
Hello

I want to upload and store a file in local tomcat server file server (something like CKEditor).

So I've created a portlet.
These are my important files:

MyUploadFilePortlet.java:
package com.mine.portlets;

import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.util.PortalUtil;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletException;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;

import java.io.File;
import java.io.IOException;

/**
 * Portlet implementation class MyUploadFilePortlet
 */
public class MyUploadFilePortlet extends GenericPortlet {
 
	protected String editJSP;
	protected String viewJSP;

	private static Log _log = LogFactoryUtil.getLog(MyUploadFilePortlet.class);

	public void init() {
		editJSP = getInitParameter("edit-jsp");
		viewJSP = getInitParameter("view-jsp");
    }

	public void processAction(
    	ActionRequest actionRequest, ActionResponse actionResponse)
		throws IOException, PortletException {

		String description = actionRequest.getParameter("description");

		UploadPortletRequest lUploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);

		if (lUploadPortletRequest.getFileName("file") != null &amp;&amp; !"".equals(lUploadPortletRequest.getFileName("file"))) {
			File file = lUploadPortletRequest.getFile("file");
			String fileName = lUploadPortletRequest.getFileName("file");
			file.setLastModified(System.currentTimeMillis());
			String fileAbsPath = file.getAbsolutePath();

			PortletPreferences prefs = actionRequest.getPreferences();

			prefs.setValue("VIDEODESCRIPTION", description);
			prefs.setValue("VIDEOURL", fileAbsPath);
			prefs.store();

			System.out.println("VIDEODESCRIPTION=" + description + " path=" + fileAbsPath + " file name=" + fileName);
		}
	}
        
	public void doEdit(
		RenderRequest renderRequest, RenderResponse renderResponse)
		throws IOException, PortletException {

		include(editJSP, renderRequest, renderResponse);
	}
        
	public void doView(
		RenderRequest renderRequest, RenderResponse renderResponse)
		throws IOException, PortletException {

		PortletPreferences prefs = renderRequest.getPreferences();

		String defaultValue = "";

		String description = (String) prefs.getValue("VIDEODESCRIPTION", defaultValue);
		String fileAbsPath = (String) prefs.getValue("VIDEOURL", defaultValue);

		renderRequest.setAttribute("ATTRIBUTE_VIDEODESCRIPTION", description);
		renderRequest.setAttribute("ATTRIBUTE_VIDEOURL", fileAbsPath);

		include(viewJSP, renderRequest, renderResponse);
	}

    protected void include(
    	String path, RenderRequest renderRequest,
    	RenderResponse renderResponse)
		throws IOException, PortletException {

        PortletRequestDispatcher portletRequestDispatcher = getPortletContext().getRequestDispatcher(path);

        if (portletRequestDispatcher == null) {
            _log.error(path + " is not a valid include");
        }
        else {
            portletRequestDispatcher.include(renderRequest, renderResponse);
        }
    }
}

view.jsp
&lt;%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %&gt;

<portlet:defineobjects />

&lt;%
String description = (String)request.getAttribute("ATTRIBUTE_VIDEODESCRIPTION");
String fileAbsPath = (String)request.getAttribute("ATTRIBUTE_VIDEOURL");
%&gt;

<h3>View mode</h3>
<p>video description: &lt;%= description %&gt;</p>
<p>video path: &lt;%= fileAbsPath %&gt;</p>

edit.jsp
&lt;%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %&gt;

<portlet:defineobjects />

<h3>Edit mode</h3>
<form action="<portlet:actionURL />" method="POST" name="<portlet:namespace />fm" enctype="multipart/form-data">
	<input type="text" name="<portlet:namespace />description"><br>
	<input type="file" name="<portlet:namespace />file"><br>
	<input type="submit">
</form>


So what I want to do exactly is play a video file in view mode.

But my first step is to store uploaded file in local server file system. The form for doing that is en edit mode. So far, in view mode I can get absolute path of the file, file name etc...

How to store an uploaded file ?

I've search through the forum but answers found did not work for me. I've tried DiskFileItemFactory class but I'm missing a lot of things.

Please help.


Liferay 6.1 provides video playiing. You can use Documents & Media portlet to store your file and then use built-in player.