My file upload is not working, urgent, I need help!

745 views
Skip to first unread message

kyute_shana

unread,
Jun 12, 2008, 10:52:40 PM6/12/08
to Google Web Toolkit
Hey guys, it's me again, I need help with the file uploading..It's not
working, whenever I click submit, there's a dialog box that comes out
and says that the file I'm calling is not available. Please help me, I
need to get everything done on the 17th and I have only 1 workday
left... :((

So here's my code for the Client Side part: filename: LoadCsvUI.java

package com.omega.payroll.client.loadcsv;

import java.util.ArrayList;
import java.util.Iterator;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.InvocationException;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.TextBox;
import com.omega.payroll.client.util.CalendarPopup;
import com.google.gwt.user.client.ui.ChangeListener;
import com.google.gwt.user.client.ui.ClickListener;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FormHandler;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormSubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormSubmitEvent;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.omega.payroll.client.Sink;

public class LoadCsvUI extends Sink implements ClickListener,
FormHandler {

private VerticalPanel mainPanel = new VerticalPanel();

private FlexTable t = new FlexTable();

private Button btnSubmit = new Button("Submit");

final FormPanel form = new FormPanel();

private boolean isMultiplePeriods = false;

final FileUpload fileUpload = new FileUpload();

public static SinkInfo init(boolean isSubSink) {
return new SinkInfo("Load Csv","", isSubSink) {
public Sink createInstance() {
return new LoadCsvUI();
}
};
}

public LoadCsvUI() {

mainPanel.setWidth("100%");
t.setStyleName("gwt-Label");

form.setWidget(fileUpload);
t.setWidget(2,1,btnSubmit);

form.setEncoding( FormPanel.ENCODING_MULTIPART );
form.setMethod( FormPanel.METHOD_POST);
form.setAction("/LoadCsvServiceImpl");

btnSubmit.addClickListener(this);

form.addFormHandler(this);

mainPanel.add(form);
mainPanel.add(t);

initWidget(mainPanel);
}

public void onShow(ArrayList args) {

}

public void onHide() {

}

public void onClick(Widget sender) {
form.submit();

}

public void onSubmit(FormSubmitEvent event) {
if (fileUpload.getFilename().length() == 0)
{
Window.alert("There is no file, Please choose one.");
event.setCancelled(true);
}
else if (!fileUpload.getFilename().endsWith(".csv"))
{
Window.alert("Please specify a file ending with '.csv'.");
event.setCancelled(true);
}

}

public void onSubmitComplete(FormSubmitCompleteEvent event) {
Window.alert(event.getResults());

}
}

Here's for the server side: filename LoadCsvImpl.java

package com.omega.payroll.server;

import java.util.*;
import java.io.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.*;
import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.http.*;


public class LoadCsvServiceImpl extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
static final Logger log =
Logger.getLogger("com.omega.payroll.server.LoadCsvServiceImpl");

private int maxSize = 100000;
private String acceptedType = new String("csv");
private boolean success = false;
private int counter = 0;
private List items = null;
private Iterator it = items.iterator();
private FileItemFactory itemFactory = new DiskFileItemFactory();
private ServletFileUpload upload = new
ServletFileUpload( itemFactory );


public void doPost( HttpServletRequest request ,
HttpServletResponse response ) throws ServletException,IOException {
System.out.println("doPost()");
try{
items = upload.parseRequest(request);
}
catch( Exception e)
{
e.printStackTrace();
}
while( it.hasNext() ) {
FileItem fileItem = (FileItem) it.next();
success = processFileItem( fileItem , "uploadedFile" +
counter + ".csv" );
counter++;
}

if( !success )
response.sendError( HttpServletResponse.SC_FORBIDDEN );
else
response.setStatus( HttpServletResponse.SC_OK);
}


private boolean processFileItem( FileItem fileItem , String
filename ) {
if( !fileItem.getContentType().equals( acceptedType ) )
return false;

if( fileItem.getSize() > maxSize )
return false;

String basePath = new String("/opt/omega-payroll-1.3/");
File file = new File( basePath + filename );
try{
fileItem.write( file );
}
catch( Exception e){
e.printStackTrace();
}
return true;
}
}

and this is for the web.xml:

<servlet>
<servlet-name>LoadCsvService</servlet-name>
<servlet-class>
com.omega.payroll.server.LoadCsvServiceImpl
</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>LoadCsvService</servlet-name>
<url-pattern>/LoadCsvService</url-pattern>
</servlet-mapping>

it's not working....T_T please help!

Oh, and do you still need a service and serviceAsync file for this?

Thomas Broyer

unread,
Jun 13, 2008, 5:21:19 AM6/13/08
to Google Web Toolkit

On 13 juin, 04:52, kyute_shana <kyute_sh...@yahoo.com> wrote:
> Hey guys, it's me again, I need help with the file uploading..It's not
> working, whenever I click submit, there's a dialog box that comes out
> and says that the file I'm calling is not available. Please help me, I
> need to get everything done on the 17th and I have only 1 workday
> left... :((
[...]
> final FileUpload fileUpload = new FileUpload();
[...]
> public LoadCsvUI() {
>
> mainPanel.setWidth("100%");
> t.setStyleName("gwt-Label");
>
> form.setWidget(fileUpload);
> t.setWidget(2,1,btnSubmit);
>
> form.setEncoding( FormPanel.ENCODING_MULTIPART );
> form.setMethod( FormPanel.METHOD_POST);
> form.setAction("/LoadCsvServiceImpl");
>
> btnSubmit.addClickListener(this);
>
> form.addFormHandler(this);
>
> mainPanel.add(form);
> mainPanel.add(t);
>
> initWidget(mainPanel);
> }

If you don't set the FileUpload's name (fileUpload.setName(...), as
with any other "form widget"), you'll never send the file to the the
server.

Might it be your problem?

Kevin O'Neill

unread,
Jun 13, 2008, 12:14:00 AM6/13/08
to Google-We...@googlegroups.com
Your servlet has a few, to put it kindly, problems. My guess is that if you take a look at the appropriate log file you'll find there is a null pointer exception when the servlet instance is created. At the very least, success, items and it should definitely be local variables in doPost.

-k.

ps: It's a bit of a tradition to use a = "foo" for constant strings rather than a = new String("foo"). 

kyute_shana

unread,
Jun 15, 2008, 8:38:44 PM6/15/08
to Google Web Toolkit
ok...I did what you guys said, but I still have an error....here:

[ INFO] 37:04 (ApplicationContext.java:log:636)
Marking servlet LoadCsvService as unavailable

[ERROR] 37:04 (StandardWrapperValve.java:invoke:145)
Allocate exception for servlet LoadCsvService

java.lang.NullPointerException
at
com.omega.payroll.server.LoadCsvServiceImpl.<init>(LoadCsvServiceImpl.java:
26)
at
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:
39)
at
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:
27)
at java.lang.reflect.Constructor.newInstance(Constructor.java:
494)
at java.lang.Class.newInstance0(Class.java:350)
at java.lang.Class.newInstance(Class.java:303)
at
org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:
1048)
at
org.apache.catalina.core.StandardWrapper.allocate(StandardWrapper.java:
750)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:
130)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:
178)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:
407)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:
126)
at
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:
105)
at
org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:
107)
at
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:
148)
at
org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:
856)
at org.apache.coyote.http11.Http11Protocol
$Http11ConnectionHandler.processConnection(Http11Protocol.java:744)
at
org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:
527)
at
org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:
80)
at org.apache.tomcat.util.threads.ThreadPool
$ControlRunnable.run(ThreadPool.java:684)
at java.lang.Thread.run(Thread.java:595)

Sorry guys, I'm having a really hard time understanding GWT... :(
> > Oh, and do you still need a service and serviceAsync file for this?- Hide quoted text -
>
> - Show quoted text -

Kevin O'Neill

unread,
Jun 15, 2008, 8:57:20 PM6/15/08
to Google-We...@googlegroups.com
Your problem isn't gwt but a seemingly lack of understanding
fundemental java programming.

In your field initializers you're assigning null to items, then in the
very next line dereferencing it. This is the likely source of your
null pointer exception.

> private List items = null;
> private Iterator it = items.iterator();

GWT is a javascript framework for java developers. If you're not
already a competent java developer then I'd suggest switching to
something more inline with your skill set.

-k.

kyute_shana

unread,
Jun 15, 2008, 10:58:06 PM6/15/08
to Google Web Toolkit
If I had a choice, I'd do that...But unfortunately, I don't
have...Thanks for your help anyways...
Message has been deleted

kyute_shana

unread,
Jun 16, 2008, 3:52:07 AM6/16/08
to Google Web Toolkit
So I got a new error....solved the previous one....

java.lang.NoClassDefFoundError: javax/servlet/ServletInputStream
at
org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:
126)
at
com.omega.payroll.server.LoadCsvServiceImpl.doPost(LoadCsvServiceImpl.java:
38)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:
709)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:
802)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:
252)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:
173)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:
213)
Whew...this is harder than I thought...but I'm willing to learn!!!
> > -k.- Hide quoted text -

gregor

unread,
Jun 16, 2008, 7:50:16 AM6/16/08
to Google Web Toolkit
Hi Kyute,

>
> java.lang.NoClassDefFoundError: javax/servlet/ServletInputStream
> at
> org.apache.commons.fileupload.servlet.ServletFileUpload.parseRequest(ServletFileUpload.java:
> 126)

means that you do not have javax.servlet.* in your classpath. Download
one of the Java EE jars from here (if you don't already have one):

http://java.sun.com/products/servlet/download.html

and add it to your classpath. Then ServletInputStream will be
avaialble to your servlet.

regards
gregor

kyute_shana

unread,
Jun 16, 2008, 8:47:15 PM6/16/08
to Google Web Toolkit
Hey Gregor! Thanks for helping me again!!! You are really a great
help!

Anyways, I found out that I already have the servlet, the javax-
servlet.jar, the servlet-api.jar and I placed them in my
classpath...but the same error appears...

This one is tough!

gregor

unread,
Jun 17, 2008, 5:57:52 AM6/17/08
to Google Web Toolkit
ServletInputStream is in javax-servlet.jar, so if this jar was in your
classpath you would not get this error. If you are running in hosted
mode you can check this by looking at your shell command line (whether
you do this yourself or you use an IDE that generates it for you). It
should look something like:

java -cp "%~dp0\src;%~dp0\bin;%~dp0\../../gwt-user.jar;%~dp0\../../gwt-
dev-windows.jar" com.google.gwt.dev.GWTShell -out "%~dp0\www" %*
com.google.gwt.sample.kitchensink.KitchenSink/KitchenSink.html

you need to make sure that javax-servlet.jar (or another jar that also
contains the javax.servlet package) is present in the -cp (or -
classpath) arguement. IDE's differ in the way you set up GWT I believe
(I use Intellij), but if the jar is listed as a library for your
project it doesn't necessarily mean it's included in the GWTShell
start script.

skv

unread,
Jun 17, 2008, 8:24:38 AM6/17/08
to Google Web Toolkit
I recommend you to have a look to this blog post, it worked for my
file upload servlet :)
http://home.izforge.com/index.php/2006/10/29/295-handling-file-uploads-with-the-google-web-toolkit

Another thing, remember to include in the HttpServletResponse of your
servlet the content type.
Something like

response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");

it will save you lot of debug ;)


Marco

kyute_shana

unread,
Jun 17, 2008, 9:15:37 AM6/17/08
to Google Web Toolkit
Thanks a million Gregor! I'd be able to try this tomorrow! Can't wait!
This might be the solution.

Another question, where exactly should I place the javax-servlet.jar?
What particular directory? I referred to some posts and they said that
the .jar should be somewhere in jre\lib\ext and others said it should
be in the WEB-INF\lib of my web project...I'm getting really
confused...

Thanks once again!!!!

kyute_shana

unread,
Jun 17, 2008, 9:18:05 AM6/17/08
to Google Web Toolkit
Thanks for the link Marco!!! I'll take a look at this as soon as I get
to work!!!

Alright, I'll do that...Wait, what if the file being uploaded is
in .CSV? what should I put in the response.Content Type()?

Sorry for all the stupid questions, I'm still in the process of
reviewing my Java lessons and I'm new to this GWT thing...

On Jun 17, 8:24 pm, skv <marco....@gmail.com> wrote:
> I recommend you to have a look to this blog post, it worked for my
> file upload servlet :)http://home.izforge.com/index.php/2006/10/29/295-handling-file-upload...

gregor

unread,
Jun 17, 2008, 9:55:27 AM6/17/08
to Google Web Toolkit

>
> Another question, where exactly should I place the javax-servlet.jar?
> What particular directory? I referred to some posts and they said that
> the .jar should be somewhere in jre\lib\ext and others said it should
> be in the WEB-INF\lib of my web project...I'm getting really
> confused...
>

In Hosted mode: Doesn't matter where it goes so long as its path in
the -cp arg of the GWTShell start script points to it correctly. WEB-
INF etc is irrelevant for hosted mode. The reason it appears you need
to do this is because GWTShell uses its own embedded Tomcat version to
run hosted mode and this obviously doesn't include the javax.servlet
stuff in its classpath.

In deployed (web) mode:

1) You may not need to package javax-servlet.jar when you deploy to
your own Tomcat instance (or application server) - it will most likely
already have it loaded in the main classpath. If so better to use that
rather than introduce a second version (which may cause problems) so I
would try deploying without it first, only add it if you need to (i.e.
get the same exception).

2) If you do need to add it then you can put in WEB-INF/lib as with
any library jar as you say.

3) IMO the best and simplest way to deploy is to use an Ant build
script to make a WAR file. Then you just copy it to your app servers
deployment directory and off it goes. Look up e.g. "ant build.xml
web.xml" on the forum - there's loads of examples on how to do this.

4) You will need to make sure your servlet mappings in web.xml are
exactly right or your servlet will get not called properly. A lot of
people have trouble with this to start with (largely because you don't
have to worry about it in hosted mode). Again look it up on the forum
- you'll have to patiently plod through the detail of this I'm afraid.

Good luck
gregor

kyute_shana

unread,
Jun 18, 2008, 12:48:54 AM6/18/08
to Google Web Toolkit
I did what you guys told me, and still not solved....I'm kinda losing
hope now... :( My deadline's coming.......

kyute_shana

unread,
Jun 18, 2008, 1:45:31 AM6/18/08
to Google Web Toolkit
I placed the javax.servler.jar in the WEB-INF/lib...then I placed the
path in the shell.cmd and compile.cmd.....nothing happened....still
same error...and this appeared:

>See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

What's wrong this time?

marco skv

unread,
Jun 18, 2008, 3:55:22 AM6/18/08
to Google Web Toolkit
Doesn't matter the type of file that you upload. Setting ContentType
is important for the response. So you can check on the client if the
upload completed successfully or not.

Have a look of a simple doPost method.

response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");

FileItem uploadItem = getFileItem(request);
if (uploadItem == null) {
response.getWriter().write("File not uploaded correctly");
return;
}

// save the file to disk
File file = saveFile(uploadItem, getServletContext());

if (file == null) {
response.getWriter().write("File upload error");
return;
}

response.getWriter().write("File uploaded successfully.");
response.flushBuffer();


Marco

kyute_shana

unread,
Jun 18, 2008, 5:28:07 AM6/18/08
to Google Web Toolkit
ok thanks.....

> File file = saveFile(uploadItem, getServletContext());

Eclipse says that I need to create a method saveFile, so I have to
create an AsynCallback and a Service file?

same with:
>FileItem uploadItem = getFileItem(request);

Eclipse says method is undefined.....

kyute_shana

unread,
Jun 18, 2008, 6:05:04 AM6/18/08
to Google Web Toolkit
I wrote what you said, still the same error.....NoClassDefFoundError

Also, it's looking for a method saveFile();

Dang! My deadline's on Friday...Please help!!!
> ...
>
> read more »

marco skv

unread,
Jun 18, 2008, 7:59:05 AM6/18/08
to Google Web Toolkit
That was a snippet of code from my UploadServlet. Not the entire
servlet ;)

However, this is a stripped version of the missing methods

/**
* Return the first FileItem of a HTTPServletRequest
* @param request The HTTPServletRequest for a file upload operation
* @return The first file of the file upload request
*/
@SuppressWarnings("unchecked")
private FileItem getFileItem(HttpServletRequest request) {
ServletFileUpload upload = Utility.setUploadOptions(request);

try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> it = items.iterator();
FileItem item = (FileItem) it.next();
return item;
}
catch (FileUploadException e) {
return null;
}
}


and this is the SaveFile

/**
* Save a file on a directory of the server.
* @param item file to save
* @param sc Servlet context
* @return error code
*/
public File saveFile(FileItem fileItem, ServletContext sc) {
try {
File file = new File(sc.getRealPath("/") + "AN_UNPLOAD_DIR",
fileItem.getName());
fileItem.write(file);
return file;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}


You should have a look to my previous link, and also to this library:
http://commons.apache.org/fileupload/

Marco
> ...
>
> read more »

kyute_shana

unread,
Jun 18, 2008, 8:23:41 PM6/18/08
to Google Web Toolkit
I can't check if the code's correct cause I still keep getting the
"NoClassDefFoundError: javax/servlet/ServletInputStream", which is
really annoying me. I did everything that you and gregor told me plus
those that I've read from other posts...but still nothing worked. :'(

kyute_shana

unread,
Jun 18, 2008, 10:41:47 PM6/18/08
to Google Web Toolkit
Ok now, managed to fix the NoClassDef error...I got a new one...

HTTP Status 403...says access is forbidden....what is it?
> ...
>
> read more »

kyute_shana

unread,
Jun 18, 2008, 11:29:11 PM6/18/08
to Google Web Toolkit
It's running now!!! Thanks to Marco and Gregor and to those who
helped!!!!!!! Thanks!!!!!!

Now, going to CSV parsing.....
> ...
>
> read more »

walden

unread,
Jun 19, 2008, 8:11:58 AM6/19/08
to Google Web Toolkit
Please think twice before posting your CSV parsing questions here.
Please.
> ...
>
> read more »- Hide quoted text -

kyute_shana

unread,
Jun 19, 2008, 7:56:51 PM6/19/08
to Google Web Toolkit
I'm not posting it here.....I got separate thread for it...
> ...
>
> read more »

kyute_shana

unread,
Jul 28, 2008, 5:09:27 AM7/28/08
to Google Web Toolkit
Hey Guys, I'm back..

I was just wondering why my file upload won't work in IE but works in
Firefox.

I get the file not found error...

Here's where I get and save the file:

public void doPost( HttpServletRequest request , HttpServletResponse
response ) throws ServletException,IOException{

response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");

FileItem uploadItem = getFileItem(request);

if (uploadItem == null)
{
response.getWriter().write("File not uploaded
correctly");
return;
}

// save the file to disk

File file = saveFile(uploadItem);

if (file == null)
{
response.getWriter().write("File upload error");
return;
}

try
{
parseFile(file);
}
catch (SQLException e)
{
e.printStackTrace();
}

response.getWriter().write("File uploaded successfully.");
response.flushBuffer();

}

/**
* Return the first FileItem of a HTTPServletRequest
* @param request The HTTPServletRequest for a file upload
operation
* @return The first file of the file upload request
*/
@SuppressWarnings("unchecked")

private FileItem getFileItem(HttpServletRequest request) {

try
{
List<FileItem> items =
upload.parseRequest(request);
Iterator<FileItem> it = items.iterator();
FileItem item = (FileItem) it.next();
return item;
}

catch (FileUploadException e)
{
e.printStackTrace();
return null;
}
}

/**
* Save a file on a directory of the server.
* @param item file to save
* @param sc Servlet context
* @return error code
*/
public File saveFile(FileItem fileItem) {

try
{
File file = new File("C:/opt/omega-
payroll-1.3/"+ fileItem.getName());
fileItem.write(file);
return file;
}

catch (Exception e)
{
e.printStackTrace();
return null;
}
}

Thanks!
Reply all
Reply to author
Forward
0 new messages