Foren

Home » Liferay Portal » English » 3. Development

Kombinierte Ansicht Flache Ansicht Baumansicht
Threads [ Zurück | Nächste ]
toggle
Rad One
Upload a file and store in server
21. April 2011 04:26
Antwort

Rad One

Rang: New Member

Nachrichten: 1

Eintrittsdatum: 21. April 2011

Neue Beiträge

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:
 1package com.mine.portlets;
 2
 3import com.liferay.portal.kernel.log.Log;
 4import com.liferay.portal.kernel.log.LogFactoryUtil;
 5import com.liferay.portal.kernel.upload.UploadPortletRequest;
 6import com.liferay.portal.util.PortalUtil;
 7
 8import javax.portlet.ActionRequest;
 9import javax.portlet.ActionResponse;
10import javax.portlet.GenericPortlet;
11import javax.portlet.PortletException;
12import javax.portlet.PortletPreferences;
13import javax.portlet.PortletRequestDispatcher;
14import javax.portlet.RenderRequest;
15import javax.portlet.RenderResponse;
16
17import java.io.File;
18import java.io.IOException;
19
20/**
21 * Portlet implementation class MyUploadFilePortlet
22 */
23public class MyUploadFilePortlet extends GenericPortlet {
24
25    protected String editJSP;
26    protected String viewJSP;
27
28    private static Log _log = LogFactoryUtil.getLog(MyUploadFilePortlet.class);
29
30    public void init() {
31        editJSP = getInitParameter("edit-jsp");
32        viewJSP = getInitParameter("view-jsp");
33    }
34
35    public void processAction(
36        ActionRequest actionRequest, ActionResponse actionResponse)
37        throws IOException, PortletException {
38
39        String description = actionRequest.getParameter("description");
40
41        UploadPortletRequest lUploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);
42
43        if (lUploadPortletRequest.getFileName("file") != null && !"".equals(lUploadPortletRequest.getFileName("file"))) {
44            File file = lUploadPortletRequest.getFile("file");
45            String fileName = lUploadPortletRequest.getFileName("file");
46            file.setLastModified(System.currentTimeMillis());
47            String fileAbsPath = file.getAbsolutePath();
48
49            PortletPreferences prefs = actionRequest.getPreferences();
50
51            prefs.setValue("VIDEODESCRIPTION", description);
52            prefs.setValue("VIDEOURL", fileAbsPath);
53            prefs.store();
54
55            System.out.println("VIDEODESCRIPTION=" + description + " path=" + fileAbsPath + " file name=" + fileName);
56        }
57    }
58       
59    public void doEdit(
60        RenderRequest renderRequest, RenderResponse renderResponse)
61        throws IOException, PortletException {
62
63        include(editJSP, renderRequest, renderResponse);
64    }
65       
66    public void doView(
67        RenderRequest renderRequest, RenderResponse renderResponse)
68        throws IOException, PortletException {
69
70        PortletPreferences prefs = renderRequest.getPreferences();
71
72        String defaultValue = "";
73
74        String description = (String) prefs.getValue("VIDEODESCRIPTION", defaultValue);
75        String fileAbsPath = (String) prefs.getValue("VIDEOURL", defaultValue);
76
77        renderRequest.setAttribute("ATTRIBUTE_VIDEODESCRIPTION", description);
78        renderRequest.setAttribute("ATTRIBUTE_VIDEOURL", fileAbsPath);
79
80        include(viewJSP, renderRequest, renderResponse);
81    }
82
83    protected void include(
84        String path, RenderRequest renderRequest,
85        RenderResponse renderResponse)
86        throws IOException, PortletException {
87
88        PortletRequestDispatcher portletRequestDispatcher = getPortletContext().getRequestDispatcher(path);
89
90        if (portletRequestDispatcher == null) {
91            _log.error(path + " is not a valid include");
92        }
93        else {
94            portletRequestDispatcher.include(renderRequest, renderResponse);
95        }
96    }
97}

view.jsp
 1<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
 2
 3<portlet:defineObjects />
 4
 5<%
 6String description = (String)request.getAttribute("ATTRIBUTE_VIDEODESCRIPTION");
 7String fileAbsPath = (String)request.getAttribute("ATTRIBUTE_VIDEOURL");
 8%>
 9
10<h3>View mode</h3>
11<p>video description: <%= description %></p>
12<p>video path: <%= fileAbsPath %></p>

edit.jsp
 1<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
 2
 3<portlet:defineObjects />
 4
 5<h3>Edit mode</h3>
 6<form action="<portlet:actionURL />" method="POST" name="<portlet:namespace />fm" enctype="multipart/form-data">
 7    <input type="text" name="<portlet:namespace />description" /><br />
 8    <input type="file" name="<portlet:namespace />file"><br />
 9    <input type="submit" />
10</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.
Suraj Bihari
RE: Upload a file and store in server
16. November 2011 07:07
Antwort

Suraj Bihari

Rang: Junior Member

Nachrichten: 42

Eintrittsdatum: 20. Mai 2011

Neue Beiträge

Hi Rad,

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

UploadPortlet.java
 1
 2public class UploadPortlet extends GenericPortlet{
 3
 4    protected String viewJSP;
 5    protected String process;
 6    protected Vector<?> v=null;
 7    protected String realPath=null;
 8
 9    public void init() throws PortletException {
10
11        viewJSP = getInitParameter("view-jsp");
12    }
13
14    public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException
15    { 
16
17        realPath = getPortletContext().getRealPath("/");
18        System.out.println(realPath);
19
20        byte[] bytes = null;
21        PortletContext portletContext = request.getPortletSession().getPortletContext();
22        try{
23
24            UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request);
25            String sourceFileName =uploadRequest.getFileName("fileName");
26            File file = uploadRequest.getFile("fileName");
27            try {
28                bytes = FileUtil.getBytes(file);
29            } catch (IOException e2) {            
30                e2.printStackTrace();
31            }
32            File newFile=null;
33
34            if ((bytes != null) && (bytes.length > 0)) {
35
36                try {
37
38                    System.out.println(sourceFileName);
39
40                    newFile = new File(realPath+"html/uploads/"+sourceFileName);
41                    FileInputStream fileInputStream = new FileInputStream(file);
42                    FileOutputStream fileOutputStream = new FileOutputStream(newFile);            
43                    fileInputStream.read(bytes);       
44                   
45                    String value = new String(bytes);
46                    System.out.println(value);
47                   
48                    fileOutputStream.write(bytes, 0, bytes.length);                   
49                    fileOutputStream.close();
50                    fileInputStream.close();
51                }
52                catch (FileNotFoundException e) {
53                    System.out.println("File Not Found.");               
54                    e.printStackTrace();
55                }
56                catch (IOException e1){
57                    System.out.println("Error Reading The File.");
58                    e1.printStackTrace();
59                }
60            }
61
62        } catch (Exception e) {
63            System.out.println("Exception::::"+e.getMessage());
64        }
65    }
66    public void render(RenderRequest request, RenderResponse response) throws PortletException, IOException
67    {
68
69        doView(request,response);
70    }
71
72    public void doView(RenderRequest request, RenderResponse response)throws IOException
73    {
74        String path=viewJSP;
75        PortletRequestDispatcher portletRequestDispatcher = getPortletContext().getRequestDispatcher(path);
76        if (portletRequestDispatcher == null) {
77            _log.error(viewJSP + " is not a valid include");
78        }
79        else{
80
81            try{
82                portletRequestDispatcher.include(request, response);
83            }
84            catch(Exception e){               
85                _log.error("Error Occured:"+e);
86            }
87        }
88    }
89    private static Log _log = LogFactoryUtil.getLog(UploadPortlet2.class);
90
91}


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
 1
 2<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
 3<%@ page language="java" contentType="text/html; charset=Windows-1256" pageEncoding="Windows-1256"%>
 4<portlet:defineObjects />
 5    <script type="text/javascript">
 6        function send()
 7        {
 8            document.UploadForm.submit();
 9        }
10    </script>
11        <h3>Upload portlet:</h3>
12       
13        <form name="UploadForm" action="<portlet:actionURL/>" enctype="multipart/form-data" method="POST">
14          <input type="file" name="fileName" size="50"><br>
15          <input type="Submit" value="Upload File" onClick="send()">
16        </form>


Good luck!
Juan Gonzalez
RE: Upload a file and store in server
14. Januar 2012 01:21
Antwort

Juan Gonzalez

LIFERAY STAFF

Rang: Liferay Legend

Nachrichten: 2947

Eintrittsdatum: 28. Oktober 2008

Neue Beiträge

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:
 1package com.mine.portlets;
 2
 3import com.liferay.portal.kernel.log.Log;
 4import com.liferay.portal.kernel.log.LogFactoryUtil;
 5import com.liferay.portal.kernel.upload.UploadPortletRequest;
 6import com.liferay.portal.util.PortalUtil;
 7
 8import javax.portlet.ActionRequest;
 9import javax.portlet.ActionResponse;
10import javax.portlet.GenericPortlet;
11import javax.portlet.PortletException;
12import javax.portlet.PortletPreferences;
13import javax.portlet.PortletRequestDispatcher;
14import javax.portlet.RenderRequest;
15import javax.portlet.RenderResponse;
16
17import java.io.File;
18import java.io.IOException;
19
20/**
21 * Portlet implementation class MyUploadFilePortlet
22 */
23public class MyUploadFilePortlet extends GenericPortlet {
24
25    protected String editJSP;
26    protected String viewJSP;
27
28    private static Log _log = LogFactoryUtil.getLog(MyUploadFilePortlet.class);
29
30    public void init() {
31        editJSP = getInitParameter("edit-jsp");
32        viewJSP = getInitParameter("view-jsp");
33    }
34
35    public void processAction(
36        ActionRequest actionRequest, ActionResponse actionResponse)
37        throws IOException, PortletException {
38
39        String description = actionRequest.getParameter("description");
40
41        UploadPortletRequest lUploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest);
42
43        if (lUploadPortletRequest.getFileName("file") != null && !"".equals(lUploadPortletRequest.getFileName("file"))) {
44            File file = lUploadPortletRequest.getFile("file");
45            String fileName = lUploadPortletRequest.getFileName("file");
46            file.setLastModified(System.currentTimeMillis());
47            String fileAbsPath = file.getAbsolutePath();
48
49            PortletPreferences prefs = actionRequest.getPreferences();
50
51            prefs.setValue("VIDEODESCRIPTION", description);
52            prefs.setValue("VIDEOURL", fileAbsPath);
53            prefs.store();
54
55            System.out.println("VIDEODESCRIPTION=" + description + " path=" + fileAbsPath + " file name=" + fileName);
56        }
57    }
58       
59    public void doEdit(
60        RenderRequest renderRequest, RenderResponse renderResponse)
61        throws IOException, PortletException {
62
63        include(editJSP, renderRequest, renderResponse);
64    }
65       
66    public void doView(
67        RenderRequest renderRequest, RenderResponse renderResponse)
68        throws IOException, PortletException {
69
70        PortletPreferences prefs = renderRequest.getPreferences();
71
72        String defaultValue = "";
73
74        String description = (String) prefs.getValue("VIDEODESCRIPTION", defaultValue);
75        String fileAbsPath = (String) prefs.getValue("VIDEOURL", defaultValue);
76
77        renderRequest.setAttribute("ATTRIBUTE_VIDEODESCRIPTION", description);
78        renderRequest.setAttribute("ATTRIBUTE_VIDEOURL", fileAbsPath);
79
80        include(viewJSP, renderRequest, renderResponse);
81    }
82
83    protected void include(
84        String path, RenderRequest renderRequest,
85        RenderResponse renderResponse)
86        throws IOException, PortletException {
87
88        PortletRequestDispatcher portletRequestDispatcher = getPortletContext().getRequestDispatcher(path);
89
90        if (portletRequestDispatcher == null) {
91            _log.error(path + " is not a valid include");
92        }
93        else {
94            portletRequestDispatcher.include(renderRequest, renderResponse);
95        }
96    }
97}

view.jsp
 1<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
 2
 3<portlet:defineObjects />
 4
 5<%
 6String description = (String)request.getAttribute("ATTRIBUTE_VIDEODESCRIPTION");
 7String fileAbsPath = (String)request.getAttribute("ATTRIBUTE_VIDEOURL");
 8%>
 9
10<h3>View mode</h3>
11<p>video description: <%= description %></p>
12<p>video path: <%= fileAbsPath %></p>

edit.jsp
 1<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
 2
 3<portlet:defineObjects />
 4
 5<h3>Edit mode</h3>
 6<form action="<portlet:actionURL />" method="POST" name="<portlet:namespace />fm" enctype="multipart/form-data">
 7    <input type="text" name="<portlet:namespace />description" /><br />
 8    <input type="file" name="<portlet:namespace />file"><br />
 9    <input type="submit" />
10</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.
Nhat Le
RE: Upload a file and store in server
5. März 2012 01:21
Antwort

Nhat Le

Rang: Junior Member

Nachrichten: 25

Eintrittsdatum: 5. März 2012

Neue Beiträge

Suraj Bihari:
Hi Rad,

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

UploadPortlet.java
 1
 2public class UploadPortlet extends GenericPortlet{
 3
 4    protected String viewJSP;
 5    protected String process;
 6    protected Vector<?> v=null;
 7    protected String realPath=null;
 8
 9    public void init() throws PortletException {
10
11        viewJSP = getInitParameter("view-jsp");
12    }
13
14    public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException
15    { 
16
17        realPath = getPortletContext().getRealPath("/");
18        System.out.println(realPath);
19
20        byte[] bytes = null;
21        PortletContext portletContext = request.getPortletSession().getPortletContext();
22        try{
23
24            UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest(request);
25            String sourceFileName =uploadRequest.getFileName("fileName");
26            File file = uploadRequest.getFile("fileName");
27            try {
28                bytes = FileUtil.getBytes(file);
29            } catch (IOException e2) {            
30                e2.printStackTrace();
31            }
32            File newFile=null;
33
34            if ((bytes != null) && (bytes.length > 0)) {
35
36                try {
37
38                    System.out.println(sourceFileName);
39
40                    newFile = new File(realPath+"html/uploads/"+sourceFileName);
41                    FileInputStream fileInputStream = new FileInputStream(file);
42                    FileOutputStream fileOutputStream = new FileOutputStream(newFile);            
43                    fileInputStream.read(bytes);       
44                   
45                    String value = new String(bytes);
46                    System.out.println(value);
47                   
48                    fileOutputStream.write(bytes, 0, bytes.length);                   
49                    fileOutputStream.close();
50                    fileInputStream.close();
51                }
52                catch (FileNotFoundException e) {
53                    System.out.println("File Not Found.");               
54                    e.printStackTrace();
55                }
56                catch (IOException e1){
57                    System.out.println("Error Reading The File.");
58                    e1.printStackTrace();
59                }
60            }
61
62        } catch (Exception e) {
63            System.out.println("Exception::::"+e.getMessage());
64        }
65    }
66    public void render(RenderRequest request, RenderResponse response) throws PortletException, IOException
67    {
68
69        doView(request,response);
70    }
71
72    public void doView(RenderRequest request, RenderResponse response)throws IOException
73    {
74        String path=viewJSP;
75        PortletRequestDispatcher portletRequestDispatcher = getPortletContext().getRequestDispatcher(path);
76        if (portletRequestDispatcher == null) {
77            _log.error(viewJSP + " is not a valid include");
78        }
79        else{
80
81            try{
82                portletRequestDispatcher.include(request, response);
83            }
84            catch(Exception e){               
85                _log.error("Error Occured:"+e);
86            }
87        }
88    }
89    private static Log _log = LogFactoryUtil.getLog(UploadPortlet2.class);
90
91}


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
 1
 2<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet" %>
 3<%@ page language="java" contentType="text/html; charset=Windows-1256" pageEncoding="Windows-1256"%>
 4<portlet:defineObjects />
 5    <script type="text/javascript">
 6        function send()
 7        {
 8            document.UploadForm.submit();
 9        }
10    </script>
11        <h3>Upload portlet:</h3>
12       
13        <form name="UploadForm" action="<portlet:actionURL/>" enctype="multipart/form-data" method="POST">
14          <input type="file" name="fileName" size="50"><br>
15          <input type="Submit" value="Upload File" onClick="send()">
16        </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
RE: Upload a file and store in server
27. Mai 2012 02:26
Antwort

Nguyen Le

Rang: New Member

Nachrichten: 11

Eintrittsdatum: 24. April 2012

Neue Beiträge

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.
Manish Kumar Jaiswal
RE: Upload a file and store in server
31. Oktober 2012 02:48
Antwort

Manish Kumar Jaiswal

Rang: Regular Member

Nachrichten: 133

Eintrittsdatum: 25. November 2008

Neue Beiträge

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 Bhanu Rastogi
RE: Upload a file and store in server
30. Januar 2013 01:37
Antwort

Chandra Bhanu Rastogi

Rang: New Member

Nachrichten: 7

Eintrittsdatum: 26. Dezember 2012

Neue Beiträge

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
Akash Jaisawal
RE: Upload a file and store in server
29. Mai 2015 05:15
Antwort

Akash Jaisawal

Rang: Regular Member

Nachrichten: 115

Eintrittsdatum: 3. März 2012

Neue Beiträge

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.