Foros de discusión

Upload file portlet (working) example with upload progress bar :-)

thumbnail
Laura Liparulo, modificado hace 11 años.

Upload file portlet (working) example with upload progress bar :-)

Junior Member Mensajes: 38 Fecha de incorporación: 30/06/12 Mensajes recientes
Hi guys I'm posting you my Portlet method and edit.jsp.. it works fine with all kind of files (max 100 MB ... ) :-) I've also included the upload progress bar :-) emoticonemoticon
emoticon

[b]<%@ 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"%>
<portlet:defineobjects />
&lt;%
String uploadProgressId = PwdGenerator.getPassword(PwdGenerator.KEY3, 4);
	PortletPreferences prefs = renderRequest.getPreferences();

%&gt;

	

<portlet:actionurl var="editCaseURL" name="uploadCase">
	<portlet:param name="jspPage" value="/edit.jsp" />
</portlet:actionurl>
<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." />
	<liferay-ui:upload-progress id="<%= uploadProgressId %>" message="uploading" redirect="<%= editCaseURL %>" />

<aui:form action="<%= editCaseURL %>" enctype="multipart/form-data" method="post">
<aui:input type="file" name="fileName" size="75" />
<input type="submit" value="<liferay-ui:message key=" upload">" onClick="&lt;%= uploadProgressId %&gt;.startProgress(); return true;"/&gt;
<!--  aui:button type="submit" value="Save" /-->
</aui:form>


<br>
<br>
<br>
<br>
<portlet:renderurl var="viewCaseURL">
	<portlet:param name="jspPage" value="/view2.jsp" />
</portlet:renderurl>

<aui:button onClick="<%=viewCaseURL%>" value="view Uploaded Case" />[/b]

this is the UPLOAD method:

[b]		public void uploadCase(ActionRequest actionRequest,
            ActionResponse actionRresponse) throws PortletException,
            IOException {
 
        String folder = getInitParameter("uploadFolder");
        realPath = getPortletContext().getRealPath("/");
 
        logger.info("RealPath" + realPath + " UploadFolder :" + folder);
        try {
            logger.info("Siamo nel try");
            UploadPortletRequest uploadRequest = PortalUtil
                    .getUploadPortletRequest(actionRequest);
         System.out.println("Size: "+uploadRequest.getSize("fileName"));
 
        if (uploadRequest.getSize("fileName")==0) {
            SessionErrors.add(actionRequest, "error");
        }
 
            String sourceFileName = uploadRequest.getFileName("fileName");
            File file = uploadRequest.getFile("fileName");
 
            logger.info("Nome file:" + uploadRequest.getFileName("fileName"));
            File newFile = null;
            newFile = new File(folder + sourceFileName);
            logger.info("New file name: " + newFile.getName());
            logger.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();
            System.out.println("file size bytes:" + size);
            System.out.println("file size Mb:" + size / 1048576);
 
            logger.info("File created: " + newFile.getName());
            SessionMessages.add(actionRequest, "success");
 
        } catch (FileNotFoundException e) {
            System.out.println("File Not Found.");
            e.printStackTrace();
            SessionMessages.add(actionRequest, "error");
        } catch (NullPointerException e) {
            System.out.println("File Not Found");
            e.printStackTrace();
            SessionMessages.add(actionRequest, "error");
        }
 
        catch (IOException e1) {
            System.out.println("Error Reading The File.");
            SessionMessages.add(actionRequest, "error");
            e1.printStackTrace();
        }
 
    }

[/b]


It works fine! the errors get properly notified when the file size exceeds 100 MB


I will widen the development... I must handle:
- multiple upload
- multipart/mixed (text + files)
- add select / options tags
- database access

:-) I will let you know
thumbnail
Hitoshi Ozawa, modificado hace 11 años.

RE: Upload file portlet (working) example with upload progress bar :-)

Liferay Legend Mensajes: 7942 Fecha de incorporación: 24/03/10 Mensajes recientes
Instead of posting partial codes here, how about making your portlet available for download from liferay.com download page? Just select "My Products" tab and "Add Product".

http://www.liferay.com/downloads/liferay-portal/community-plugins/-/software_catalog/products
thumbnail
Laura Liparulo, modificado hace 11 años.

RE: Upload file portlet (working) example with upload progress bar :-)

Junior Member Mensajes: 38 Fecha de incorporación: 30/06/12 Mensajes recientes
oh yes.
I'm still widening it.. anyway I can already share it. the problem is that I'm using "it.unicas.mammography" as package... and so on. I will make an example version and i will uploading. I'm writing my master thesis. I'm making a whole small portal from scratch for uploading, downloading and rendering ecographies. with html5, etc.
I've already worked as a java developer for a year.. I will share the project :-)
I've made this thanks to the communities :-)
thumbnail
Hitoshi Ozawa, modificado hace 11 años.

RE: Upload file portlet (working) example with upload progress bar :-)

Liferay Legend Mensajes: 7942 Fecha de incorporación: 24/03/10 Mensajes recientes
the problem is that I'm using "it.unicas.mammography" as package


Packages doesn't have to have com.liferay packages. I don't even think most community packages does.
thumbnail
Laura Liparulo, modificado hace 11 años.

RE: Upload file portlet (working) example with upload progress bar :-)

Junior Member Mensajes: 38 Fecha de incorporación: 30/06/12 Mensajes recientes
allright thanks

I still need to improve it. Now it works and I haven't found a working example so far.. and also the upload progress tags is nice.
I will upload the whole project in the end and the improved complete version of the Upload portlet within few days
Cheers
thumbnail
Ram Manusani, modificado hace 11 años.

RE: Upload file portlet (working) example with upload progress bar :-)

Regular Member Mensajes: 124 Fecha de incorporación: 27/10/11 Mensajes recientes
Laura,

Did you get a chance to upload the war file or project as mentioned. If Yes, Could you please provide me the link..


Thanks
bala malasani, modificado hace 11 años.

RE: Upload file portlet (working) example with upload progress bar :-)

New Member Mensajes: 20 Fecha de incorporación: 25/09/12 Mensajes recientes
Hi laura,
i am new to liferay i am trying to upload file by using ur code .
I have tried your code for file upload ,i got "folder" value null at line number 8 .is there any other configurations need to be done for getting folder name ? and after uploading file where it stored i have refered it at location /tomcat/Root/web-inf/My portletname/ i dint get any folder or uploaded files.

can u plz help me to resolve this issue.
thumbnail
Laura Liparulo, modificado hace 11 años.

RE: Upload file portlet (working) example with upload progress bar :-)

Junior Member Mensajes: 38 Fecha de incorporación: 30/06/12 Mensajes recientes
In the portlet.xml file you can set some parameters like this:

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

otherwise you can specify the path directly
bala malasani, modificado hace 11 años.

RE: Upload file portlet (working) example with upload progress bar :-)

New Member Mensajes: 20 Fecha de incorporación: 25/09/12 Mensajes recientes
Thanks laura for ur help.
Nitesh Phadatare, modificado hace 10 años.

RE: Upload file portlet (working) example with upload progress bar :-)

New Member Mensajes: 7 Fecha de incorporación: 10/05/13 Mensajes recientes
Thank You.
Its working for me.
But sometimes it only shows text "Uploading..." and "Done" without the actual progress bar.
I tried to add some delay in javascript before submitting form but still the problem persist.
Can you suggest me some solution?

Is it possible to show actual percentage of uploading file?
Nitesh Phadatare, modificado hace 10 años.

RE: Upload file portlet (working) example with upload progress bar :-)

New Member Mensajes: 7 Fecha de incorporación: 10/05/13 Mensajes recientes
Actually i got the problem why its happening.
Its because the images required for upload progress bar which are there in theme are not getting loaded.
So if i hit the url for those images separately in the browser and check for progress bar, it shows/works properly.
But this should not be the case because other images in theme are getting loaded but only images related to progress bar are not loaded.

What could be the solution for this?
Alessio Camillò, modificado hace 10 años.

RE: Upload file portlet (working) example with upload progress bar :-)

New Member Mensajes: 4 Fecha de incorporación: 29/08/13 Mensajes recientes
Hi laura

I used your code and it woks fine emoticon.
Is it possibile to have an example of view2.jsp called by "view Uploaded Case" button?

Thanks a lot
thumbnail
Manoj Kumar, modificado hace 10 años.

RE: Upload file portlet (working) example with upload progress bar :-)

New Member Mensajes: 3 Fecha de incorporación: 11/12/13 Mensajes recientes
Hi,

I am not able to find the place where we need to write this java method uploadCase. Can any one tell me please if we need to add this method in JSP itself or in a separate java file ?

Regards,
Manoj
Arun Kumar Purohit, modificado hace 10 años.

RE: Upload file portlet (working) example with upload progress bar :-)

New Member Mensajes: 2 Fecha de incorporación: 27/11/13 Mensajes recientes
this is the exact and error free code to upload a file in liferay...
public void uploadCase(ActionRequest actionRequest,
ActionResponse actionRresponse) throws PortletException,
IOException {

String folder = getInitParameter("uploadFolder");

String realPath = getPortletContext().getRealPath("/");

System.out.println("RealPath" + realPath +"\\" + folder);
try {

UploadPortletRequest uploadRequest = PortalUtil
.getUploadPortletRequest(actionRequest);
System.out.println("Size: "+uploadRequest.getSize("fileName"));

if (uploadRequest.getSize("fileName")==0) {
SessionErrors.add(actionRequest, "error");
}

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

System.out.println("Nome file:" + uploadRequest.getFileName("fileName"));
File newFolder = null;
newFolder = new File(realPath +"\\" + folder);
if(!newFolder.exists()){
newFolder.mkdir();
}
File newfile = null;
newfile = new File(newFolder.getAbsoluteFile()+"\\"+sourceFileName);
System.out.println("New file name: " + newfile.getName());
System.out.println("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();
System.out.println("file size bytes:" + size);
System.out.println("file size Mb:" + size / 1048576);

System.out.println("File created: " + newfile.getName());
SessionMessages.add(actionRequest, "success");

} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
} catch (NullPointerException e) {
System.out.println("File Not Found");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}

catch (IOException e1) {
System.out.println("Error Reading The File.");
SessionMessages.add(actionRequest, "error");
e1.printStackTrace();
}

}
juan meza, modificado hace 9 años.

RE: Upload file portlet (working) example with upload progress bar :-)

Regular Member Mensajes: 228 Fecha de incorporación: 6/01/14 Mensajes recientes
Hi, thanks for sharing this!

quick question
what can i do to add aditional parameters? the action in the controller doesnt seem to get them, they always return null, only the file works

thanks!
juan meza, modificado hace 9 años.

RE: Upload file portlet (working) example with upload progress bar :-)

Regular Member Mensajes: 228 Fecha de incorporación: 6/01/14 Mensajes recientes
juan meza:
Hi, thanks for sharing this!

quick question
what can i do to add aditional parameters? the action in the controller doesnt seem to get them, they always return null, only the file works

thanks!


to answer my own question, you can get the parameters like this:

UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request);
			
String param1 = ParamUtil.getString(uploadRequest, "param1");
String param2 = ParamUtil.getString(uploadRequest, "param2");

String sourceFileName = uploadRequest.getFileName("documento");
File file = uploadRequest.getFile("documento"); 
Paolo Aprile, modificado hace 9 años.

RE: Upload file portlet (working) example with upload progress bar :-)

New Member Mensajes: 2 Fecha de incorporación: 15/07/14 Mensajes recientes
Hi Laura! Hi everyone!
I'm trying to use your code, Laura, but I get this:

ERROR [http-bio-8080-exec-175][render_portlet_jsp:157] java.lang.NoSuchMethodException: com.liferay.util.bridges.mvc.MVCPortlet.uploadCase(javax.portlet.ActionRequest, javax.portlet.ActionResponse)

Do you know how I could solve the problem? Could you help me?


Paolo
Kim Capa, modificado hace 9 años.

RE: Upload file portlet (working) example with upload progress bar :-)

Junior Member Mensajes: 49 Fecha de incorporación: 31/07/14 Mensajes recientes
Hi..

Where should i put the upload method? im new to liferay.. plss help me..

kim
thumbnail
Sai Sriharsha Kasturi, modificado hace 9 años.

RE: Upload file portlet (working) example with upload progress bar :-)

Junior Member Mensajes: 34 Fecha de incorporación: 21/10/12 Mensajes recientes
You should place it in the controller
thumbnail
Akash Jaisawal, modificado hace 8 años.

RE: Upload file portlet (working) example with upload progress bar :-)

Regular Member Mensajes: 141 Fecha de incorporación: 3/03/12 Mensajes recientes
I used this code to upload a file in the system.

public void uploadCase(ActionRequest actionRequest,
ActionResponse actionRresponse) throws PortletException,
IOException {

String folder = getInitParameter("uploadFolder");

String realPath = getPortletContext().getRealPath("/");

System.out.println("RealPath" + realPath +"\\" + folder);
try {

UploadPortletRequest uploadRequest = PortalUtil
.getUploadPortletRequest(actionRequest);
System.out.println("Size: "+uploadRequest.getSize("fileName"));

if (uploadRequest.getSize("fileName")==0) {
SessionErrors.add(actionRequest, "error");
}

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

System.out.println("Nome file:" + uploadRequest.getFileName("fileName"));
File newFolder = null;
newFolder = new File(realPath +"\\" + folder);
if(!newFolder.exists()){
newFolder.mkdir();
}
File newfile = null;
newfile = new File(newFolder.getAbsoluteFile()+"\\"+sourceFileName);
System.out.println("New file name: " + newfile.getName());
System.out.println("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();
System.out.println("file size bytes:" + size);
System.out.println("file size Mb:" + size / 1048576);

System.out.println("File created: " + newfile.getName());
SessionMessages.add(actionRequest, "success");

} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
} catch (NullPointerException e) {
System.out.println("File Not Found");
e.printStackTrace();
SessionMessages.add(actionRequest, "error");
}

catch (IOException e1) {
System.out.println("Error Reading The File.");
SessionMessages.add(actionRequest, "error");
e1.printStackTrace();
}

} 

and its creating files under the liferay>tomcat>webapps>abcPortlet>

how can we define the path where we want to save the file in that code.

Regards\
Akash
thumbnail
Akash Jaisawal, modificado hace 8 años.

RE: Upload file portlet (working) example with upload progress bar :-)

Regular Member Mensajes: 141 Fecha de incorporación: 3/03/12 Mensajes recientes
Hi...

I used this code to save file on the given location.
1
 2public void uploadCase(ActionRequest actionRequest,
 3ActionResponse actionRresponse) throws PortletException,
 4IOException {
 5
 6String folder = getInitParameter("uploadFolder");
 7
 8String realPath = getPortletContext().getRealPath("/");
 9
10System.out.println("RealPath" + realPath +"\\" + folder);
11try {
12
13UploadPortletRequest uploadRequest = PortalUtil
14.getUploadPortletRequest(actionRequest);
15System.out.println("Size: "+uploadRequest.getSize("fileName"));
16
17if (uploadRequest.getSize("fileName")==0) {
18SessionErrors.add(actionRequest, "error");
19}
20
21String sourceFileName = uploadRequest.getFileName("fileName");
22File file = uploadRequest.getFile("fileName");
23
24System.out.println("Nome file:" + uploadRequest.getFileName("fileName"));
25File newFolder = null;
26newFolder = new File(realPath +"\\" + folder);
27if(!newFolder.exists()){
28newFolder.mkdir();
29}
30File newfile = null;
31newfile = new File(newFolder.getAbsoluteFile()+"\\"+sourceFileName);
32System.out.println("New file name: " + newfile.getName());
33System.out.println("New file path: " + newfile.getPath());
34
35InputStream in = new BufferedInputStream(uploadRequest.getFileAsStream("fileName"));
36FileInputStream fis = new FileInputStream(file);
37FileOutputStream fos = new FileOutputStream(newfile);
38
39byte[] bytes_ = FileUtil.getBytes(in);
40int i = fis.read(bytes_);
41
42while (i != -1) {
43fos.write(bytes_, 0, i);
44i = fis.read(bytes_);
45}
46fis.close();
47fos.close();
48Float size = (float) newfile.length();
49System.out.println("file size bytes:" + size);
50System.out.println("file size Mb:" + size / 1048576);
51
52System.out.println("File created: " + newfile.getName());
53SessionMessages.add(actionRequest, "success");
54
55} catch (FileNotFoundException e) {
56System.out.println("File Not Found.");
57e.printStackTrace();
58SessionMessages.add(actionRequest, "error");
59} catch (NullPointerException e) {
60System.out.println("File Not Found");
61e.printStackTrace();
62SessionMessages.add(actionRequest, "error");
63}
64catch (IOException e1) {
65System.out.println("Error Reading The File.");
66SessionMessages.add(actionRequest, "error");
67e1.printStackTrace();
68}
69}



And now the portle saving the file under given location liferay/tomcat/webapps/abcportlet
how can i define the path if i want to save the file in some other place.
thumbnail
Vishal Srivastava, modificado hace 8 años.

RE: Upload file portlet (working) example with upload progress bar :-)

Junior Member Mensajes: 26 Fecha de incorporación: 7/07/14 Mensajes recientes
Try this Akash

In portlet.xml file
<init-param>
<name>uploadFolder</name>
<value>/home/myFolder/folderxyz</value>
</init-param>

In Your Controller get this value
String someFolder = getInitParameter("uploadFolder");

Now you have /home/myFolder/folderxyz this path in your someFolder
So this way you can give any path which you want.

Note-:
1. Why are you getting real path there is no need for that as you need to create your own folder structure
2. No need to get AbsolutePath instead try thi
newfile = new File(folder+"/"+sourceFileName+"-"+myNewFolder);
thumbnail
Enrique Valdes Lacasa, modificado hace 8 años.

RE: Upload file portlet (working) example with upload progress bar :-)

Junior Member Mensajes: 92 Fecha de incorporación: 29/07/14 Mensajes recientes
Hello guys,

I also created a file uploader portlet to upload files in Documents and Media. It displays a progress bar for each file. If you are interested on how to implement it, I explained it thoroughly in an answer for this question at Stackoverflow: Customize File Uploader in Liferay.

If you have any questions, let me know. Regards.