File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Other Open Source Projects and the fly likes Apache FileUpload Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Products » Other Open Source Projects
Bookmark "Apache FileUpload" Watch "Apache FileUpload" New topic

Apache FileUpload

Tay Thotheolh
Ranch Hand

Joined: Aug 07, 2008
Posts: 84
I am not sure if this belongs to I/O or servlet/JSP since the Apache FileUpload is an I/O and also used in servlets.

Anyway, I have a JSP form for user to select a file and hit the upload button with a textarea for comments.

The servlet would use the FileUpload to sort through for files and normal fields. The normal field would be obviously the textarea. Code is below:

Everytime it meets a file item, it converts it to a file and save it inside a FileList (ArrayList). The purpose is simply to collect all files in the arraylist and do the saving of the files when all the files are collected but before doing the saving of all files, an entry is added into the database first and if the entry fails , there is no point adding any file to a folder.

The above code loops into the ArrayList containing the files and retrieves each of them, read them as inputstream and then write them out into a folder.

The error I got is FileNotfoundException pointing that the file the input stream is trying to read is not found.

How should I modify my codes to handle the above situation ? Is there any API for the FileUpload to actually fo the write item all at once at the last moment rather than reading every file and then writing them and ocnsidering the writing depends whether the database insert is successful (when successful, write the files).
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
There are a couple of problems with this code:

- You need to get the input stream from the FileItem object; the File object you're getting it from now points to a non-existing file. So don't put File objects into the list - use the FileItem objects.

- The loop that's supposed to write the file contents doesn't actually do that (it doesn't use the buf variable).
Tay Thotheolh
Ranch Hand

Joined: Aug 07, 2008
Posts: 84
I think I figured that rather then figuring some I/O stream to write the file, maybe I iterate the items a second time after when the database insert is confirmed to be successful, to write all the items.... which means all I need is to copy the code and call the item.write() for each item. Maybe it seems the above long way around is more convenient then thinking of some 'shorter' way.
I agree. Here's the link:
subject: Apache FileUpload
jQuery in Action, 3rd edition