Skip to Main Content

Java EE (Java Enterprise Edition) General Discussion

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Problems with Apache Commons FileUpload

843842May 4 2008 — edited May 6 2008
I'm completely stymied here. I've been trying to get the Apache Commons FileUpload working with a JBoss 4.2 server, and having no luck whatsoever. The servlet is listed out here:
package com.areteinc.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

public class Filer extends HttpServlet {
	
	private Logger logger = Logger.getLogger(Filer.class);
	
	public Filer() {
		logger.setLevel(Level.DEBUG);
	}
	
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		logger.debug("Serving up a GET page...");
		PrintWriter writer = resp.getWriter();
		StringBuffer response = new StringBuffer();
		response.append("<HTML><HEAD><TITLE>JENA File Uploader</TITLE></HEAD><BODY>");
		response.append("<FORM action=\"Filer\" method=\"POST\" enctype=\"multipart/form-data\">");
		response.append("Upload file: <input type=\"file\" name=\"file1\"/><br>");
		response.append("Upload file: <input type=\"file\" name=\"file2\"/><br>");
		response.append("<input type=submit value=\"Start upload\">");
		response.append("</BODY>");
		writer.println(response);
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// First see if someone is uploading more than one file at a time...
		boolean isMultipart = ServletFileUpload.isMultipartContent(req);
		
		logger.debug("Received a POST request.  Multipart is flagged as " + isMultipart);
		
		// Create a factory for disk-based file items
		FileItemFactory factory = new DiskFileItemFactory();

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);

		// Parse the request
		try {
			List<FileItem> items = upload.parseRequest(req);
			Iterator itr = items.iterator();
			logger.debug("Size of upload is " + items.size() + " items.");
			while(itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				logger.debug("Filename is " + item.getName());
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
	}
}
When run, I hit it with a get operation, and get the form. When I put in 2 forms (in reality, all i want to do is use one, but I'm tinkering), I see nothing in items list...

-----------
Run, with 2 files selected to upload:
13:50:15,421 DEBUG [Filer] Received a POST request. Multipart is flagged as true
13:50:15,421 DEBUG [Filer] Size of upload is 0 items.

I've tried variation after variation after variation, and it jst doesn't work. I'm using commons-fileupload-1.2.1.

Help! :)

Comments

794117
I don't see a closing </form> tag in your html. Don't know if that would affect it or not.
Try putting a standard <input type="text"> control on the page to see if that gets sent along as well?
843842
Good suggestions, but unfortunately it didn't help. I put in a normal 'text' parameter, and req.getParameter("name"); returned the value. req.getParameter("file1") returns null.

I'm wondering if the encoding may be wrong - why would fileUploade be doing a 'parseRequest()' on the entire req object? Would it know which ones were files?

I'm totally fishing here. Much of that code is directly from the commons fileupload manual :-/
843842
On the client side, the client's browser must support form-based upload. Most modern browsers do, but there's no guarantee. For your case,


The servlet can use the GET method parameters to decide what to do with the upload while the POST body of the request contains the file data to parse.


When the user clicks the "Upload" button, the client browser locates the local file and sends it using HTTP POST, encoded using the MIME-type multipart/form-data. When it reaches your servlet, your servlet must process the POST data in order to extract the encoded file. You can learn all about this format in RFC 1867.


Unfortunately, there is no method in the Servlet API to do this. Fortunately, there are a number of libraries available that do. Some of these assume that you will be writing the file to disk; others return the data as an InputStream.
Jason Hunter's MultipartRequest (available from [http://www.servlets.com/])


Apache Jakarta Commons Upload (package org.apache.commons.upload) "makes it easy to add robust, high-performance, file upload capability to your servlets and web applications"


*CParseRFC1867 (available from [http://www.servletcentral.com/]).


*HttpMultiPartParser by Anil Hemrajani, at the isavvix Code Exchange


*There is a multipart/form parser availailable from Anders Kristensen ([http://www-uk.hpl.hp.com/people/ak/java/] at [http://www-uk.hpl.hp.com/people/ak/java/#utils].


*JavaMail also has MIME-parsing routines (see the Purple Servlet References).


*Jun Inamori has written a class called org.apache.tomcat.request.ParseMime which is available in the Tomcat CVS tree.


*JSPSmart has a free set of JSP for doing file upload and download.


*UploadBean by JavaZoom claims to handle most of the hassle of uploading for you, including writing to disk or memory.


There's an Upload Tag in dotJ



Once you process the form-data stream into the uploaded file, you can then either write it to disk, write it to a database, or process it as an InputStream, depending on your needs. See How can I access or create a file or folder in the current directory from inside a servlet? and other questions in the Servlets:Files Topic for information on writing files from a Servlet.


Please note: that you can't access a file on the client system directly from a servlet; that would be a huge security hole. You have to ask the user for permission, and currently form-based upload is the only way to do that.

I still have doubt if all the moentioned resources are alive or not
843842
Checkout the FAQ on commons file upload
http://commons.apache.org/fileupload/faq.html#empty-parse
1 - 4
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on Jun 3 2008
Added on May 4 2008
4 comments
878 views