Java file upload in Servlet using Apache commons FileUpload component (sample code)

This should be a very simple program, but it took me some time to figure out how to use Apache commons FileUpload component. Since nobody will read this, I put it here only for my own reference. Be careful about how to save the uploaded files to server. The HTML code for Form is too simple and can find everywhere, so the following is only the code of doPost method in servlet.

protected void doPost(HttpServletRequest res, HttpServletResponse response)
		throws ServletException, IOException {
	// Commons file upload classes are specifically instantiated
	FileItemFactory factory = new DiskFileItemFactory();
	ServletFileUpload upload = new ServletFileUpload(factory);
	ServletOutputStream out = null;
	try {
		// Parse the incoming HTTP request
		// Commons takes over incoming request at this point
		// Get an iterator for all the data that was sent
		List items = upload.parseRequest(res);
		Iterator iter = items.iterator();
		// Set a response content type
		// Setup the output stream for the return XML data
		out = response.getOutputStream();
		// Iterate through the incoming request data
		while (iter.hasNext()) {
			// Get the current item in the iteration
			FileItem item = (FileItem);
			// If the current item is an HTML form field
			if (item.isFormField()) {
				// Return an XML node with the field name and value
				out.println("this is a form data " + item.getFieldName() + "<br>");
				// If the current item is file data
			} else {
				// Specify where on disk to write the file
				// Using a servlet init param to specify location on disk
				// Write the file data to disk
				// TODO: Place restrictions on upload data
				File disk = new File("C:\\uploaded_files\\"+item.getName());
				// Return an XML node with the file name and size (in bytes)
				out.println("this is a file with name: " + item.getName());
		// Close off the response XML data and stream
		// Rudimentary handling of any exceptions
		// TODO: Something useful if an error occurs
	} catch (FileUploadException fue) {
	} catch (IOException ioe) {
	} catch (Exception e) {
Category >> JSP/JSF  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";
  • mrun

    i have downloaded the jar files but on compiling they give no main class found error


    Thanks for such a wonderful post….thanks a lot….

  • Meeta Pal

    Thanks a lot!

  • ryanlr

    Try the following:


  • Meeta Pal

    Thank for code! But it does not retrieve other data of form(like text field data of that form), please tell how to retrieve other data from form.