Forums

Home » Liferay Portal » English » 3. Development

Combination View Flat View Tree View
Threads [ Previous | Next ]
toggle
David Polites
Simple file upload with serveResource()
October 17, 2012 10:16 AM
Answer

David Polites

Rank: New Member

Posts: 2

Join Date: October 17, 2012

Recent Posts

Hi, I am very new with Liferay and have been tasked with what should be a straight forward problem to solve. However, I'm at my wits end and am hoping for some guidance here.

I am buliding a custom portlet that needs to be able to upload simple text files from the client's browser. I have seen lots of tutorials on doing it with processAction, but due to the level of javascript and interactivity we have, it is really hoped to use serveResource() to prevent page reloads. Once the file is uploaded, it needs to be temorarily stored on the web server for consumption then deleted. I have done this with php and jsp in the past in less than an hour. Learning the liferay way....I'm stumped.

Here's the portlet code:
 1    [font=Courier New]public void serveResource(ResourceRequest request, ResourceResponse response) throws PortletException, IOException {
 2        LOG.info( "Received AJAX Request" );
 3        String url = request.getParameter("command");
 4        if( null != url)
 5        {
 6            LOG.info( "Found command: " + url);
 7            if ( url.equals("message"))
 8            {
 9                // Send the message to the end point
10                processMessage( request, response );
11            }
12            else if ( url.equals("save"))
13            {
14                // Save the file to the client
15            }
16        }
17        else
18        {
19            LOG.info( "Executing Save Message...");
20            // We assume we are loading a message.
21            saveMessage( request, response );
22        }
23    }
24   
25    @Override
26
27    private void saveMessage( ResourceRequest request, ResourceResponse response ) throws IOException
28    {
29        UploadPortletRequest uploadRequest = PortalUtil.getUploadPortletRequest( request );
30       
31        InputStream inputStream = uploadRequest.getFileAsStream( "file", true );
32        String output = "";
33        try
34        {
35            output = new Scanner( inputStream ).useDelimiter( "\\A" ).next();
36        }
37        catch (Exception e)
38        {
39            e.printStackTrace();
40        }
41       
42        LOG.info( "File read in: " + output );
43    }[/font]


The input stream is always empty. I have confirmed that the file is indeed in the request headers via a development proxy. I just can't seem to refer to it in the portlet.

I am using a pure javascript file uploader from valums to get the file to the server. Below is how that is done (minus the actual valums code for the moment): javascript that performs the ajax call and how the resourceURL is created:
 1
 2[font=Courier New]<portlet:defineObjects/>
 3<liferay-theme:defineObjects/>
 4
 5<portlet:resourceURL var="tfmCall" id="DocumentServiceIssue.jsp" escapeXml="false" />
 6
 7...
 8
 9$(document).ready( function() {
10            var uploader = new qq.FileUploader({
11                element: document.getElementById("uploader"),
12                action: '<%=renderResponse.encodeURL(tfmCall.toString())%>',
13                debug: true,
14                onComplete: function() { alert("Done"); },
15                maxConnections: 1,
16                multiple: false
17            });
18         });[/font]


How do I make this work? I'll be happy to post anything else you may need.

Thank you!!
Sameer Srivastava
RE: Simple file upload with serveResource()
October 18, 2012 1:33 AM
Answer

Sameer Srivastava

Rank: New Member

Posts: 14

Join Date: August 22, 2012

Recent Posts

This code might be of help :

For View :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:ace="http://www.icefaces.org/icefaces/components"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:fn="http://java.sun.com/jsp/jstl/functions">

<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Add products via CSV</title>
</h:head>

<h:body class="ice-skin-sam">
<h:form id="addProductsForm" enctype="multipart/form-data">
<ace:fileEntry id="fileEntry" label="#{fileEntryCallbackBean.label}" fileEntryListener="#{fileEntryCallbackBean.executeListener}" absolutePath="C:\temp" styleClass="ib" />
<h:commandButton styleClass="ib" value="Submit file" />
<div class="messages-holder"><h:messages styleClass="messages" showDetail="true" /></div>
</h:form>
</h:body>
</html>

Backing bean :

package uk.co.myRetailSoftware.portal.fileUpload.bean;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.StringTokenizer;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

import org.icefaces.ace.component.fileentry.FileEntry;
import org.icefaces.ace.component.fileentry.FileEntryEvent;
import org.icefaces.ace.component.fileentry.FileEntryResults;
import org.portletfaces.bridge.GenericFacesPortlet;
import org.portletfaces.logging.Logger;
import org.portletfaces.logging.LoggerFactory;

import com.myRetailSoftware.webservices.ServiceHandlerProxy;

@ManagedBean(name="fileEntryCallbackBean")
@ViewScoped
public class FileEntryCallbackBean extends GenericFacesPortlet implements Serializable {

private static final long serialVersionUID = 1L;

private static final Logger logger = LoggerFactory
.getLogger(FileEntryCallbackBean.class);

public void executeListener(FileEntryEvent event)
{
FileEntry fileEntry = (FileEntry)event.getSource();
FileEntryResults entryResults = fileEntry.getResults();
File file = entryResults.getFiles().get(0).getFile();

try {

FileInputStream fileInputStream = new FileInputStream(file);
DataInputStream dataInputStream = new DataInputStream(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(dataInputStream));

String strLine;

while((strLine = bufferedReader.readLine()) != null){
StringTokenizer stringTokenizer = new StringTokenizer(strLine, ",");
while(stringTokenizer.hasMoreTokens()){
logger.info(stringTokenizer.nextToken());
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}

This works for me .
emoticon
Sameer
John Carter
RE: Simple file upload with serveResource()
October 18, 2012 4:10 AM
Answer

John Carter

Rank: Junior Member

Posts: 47

Join Date: October 18, 2012

Recent Posts

If file object is there in request then try below code .
1                 String fileName = uploadRequest.getFileName("file");
2                    File tempFile = uploadRequest.getFile("file");
3                    File file=new File(fileName);
4                    InputStream is = new UnsyncBufferedInputStream(new FileInputStream(tempFile));
David Polites
RE: Simple file upload with serveResource()
October 18, 2012 12:26 PM
Answer

David Polites

Rank: New Member

Posts: 2

Join Date: October 17, 2012

Recent Posts

I still get the same error. However, I did find that the file reference doesn't point to a valid path. For example, the file handle says it was written to the C:\<tomcat temp folder>\upload00004.txt. If you navigate there, that file does not exist. The folder does have write permissions. Tomcat and/or liferay actively use it.

Any thougths on that lead?
Sameer Srivastava
RE: Simple file upload with serveResource()
October 19, 2012 1:15 AM
Answer

Sameer Srivastava

Rank: New Member

Posts: 14

Join Date: August 22, 2012

Recent Posts

Can you post the view file i.e. xhtml and the backing bean here ?
John Carter
RE: Simple file upload with serveResource()
October 19, 2012 3:13 AM
Answer

John Carter

Rank: Junior Member

Posts: 47

Join Date: October 18, 2012

Recent Posts

David Polites:
I still get the same error. However, I did find that the file reference doesn't point to a valid path. For example, the file handle says it was written to the C:\<tomcat temp folder>\upload00004.txt. If you navigate there, that file does not exist. The folder does have write permissions. Tomcat and/or liferay actively use it.

Any thougths on that lead?


What all you have written is correct when we upload file in liferay it creates reference of that file in temporary folder ,if still you are getting the error then please check by using below code and try if it's worked then there must be problem in the script you have used or you have not used the enctype attribute in <aui:form/> .


 1<portlet:actionURL name="uploadFile" var="uploadFile">
 2</portlet:actionURL>
 3
 4<aui:form action="<%= uploadFile%>" enctype="multipart/form-data"  method="get" name="fm">
 5
 6<aui:fieldset>
 7    <aui:input cssClass="lfr-input-text" label="upload-file" name="file" type="file" />
 8</aui:fieldset>
 9
10<aui:button-row>
11    <aui:button  type="submit" value="import" />
12</aui:button-row>
13</aui:form>
14