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).
- 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).
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.