SWFUpload and Java Servlet Example

I have been trying to find out one good upload client over the web and it really took 3 days to me to nail down one which one best.

SWFUpload seems to be best library available as of today. I dont see they implementing java examples. Here is my attempt provide a java sample for it

This example will implement basic file upload with cancel and manual upload trigger functionality with servlet in backend

Here is sample client code

		

var swfu;

window.onload = function() {
	var settings = {
		flash_url : "swfupload/swfupload.swf",
		upload_url: "Upload",
		file_size_limit : "100 MB",
		file_types : "*.*",
		file_types_description : "All Files",
		file_upload_limit : 100,
		file_queue_limit : 0,
		custom_settings : {
			progressTarget : "fsUploadProgress",
			cancelButtonId : "btnCancel"
		},
		debug: false,

		// Button settings
		button_image_url: "swfupload/TestImageNoText_65x29.png",
		button_width: "95",
		button_height: "29",
		button_placeholder_id: "spanButtonPlaceHolder",
		button_text: 'Browse Files',
		button_text_style: ".theFont { font-size: 22; }",
		button_text_left_padding: 2,
		button_text_top_padding: 3,
		
		// The event handler functions are defined in handlers.js
		file_queued_handler : fileQueued,
		file_queue_error_handler : fileQueueError,
		upload_start_handler : uploadStart,
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadSuccess
	};

	swfu = new SWFUpload(settings);
    };


    function handleUpload(){
     var emailid = document.getElementById("email").value;
   	 swfu.setPostParams({ email:emailid });
   	 //swfu.setUploadURL("CommonsFileUploadServlet?test=234");
   	 swfu.startUpload();
 }

Here is sample screenshot

SWFUploadExample

Try downloading code from SVN from follwong location

https://linkwithweb.googlecode.com/svn/trunk/Utilities/FlashFileUpload

Make sure you have maven installed on machine before executing the below command
After downloading just run “mvn jetty:run”

and open this URL to test http://localhost:8080/FileUpload/

Advertisements

File Upload in J2ee / Servlet

Lots of people try to find some good working examples for file upload in J2ee but i rarely find any working example which can be run immedialty after downloading. Here is my Effort to create one such example which uses maven as build/test environment

/**
 * 
 */
package com.northalley.upload;

/**
 * @author ashwin kumar
 *
 */
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * @author ashwin kumar
 * 
 */
public class CommonsFileUploadServlet extends HttpServlet {
	private static final String TMP_DIR_PATH = "c:\\test";
	private File tmpDir;
	private static final String DESTINATION_DIR_PATH = "c:\\test";
	private File destinationDir;

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		tmpDir = new File(TMP_DIR_PATH);
		if (!tmpDir.isDirectory()) {
			throw new ServletException(TMP_DIR_PATH + " is not a directory");
		}
		//String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
		destinationDir = new File(DESTINATION_DIR_PATH);
		if (!destinationDir.isDirectory()) {
			throw new ServletException(DESTINATION_DIR_PATH
					+ " is not a directory");
		}

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		PrintWriter out = response.getWriter();
		response.setContentType("text/plain");
		out
				.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
		out.println();

		DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
		/*
		 * Set the size threshold, above which content will be stored on disk.
		 */
		fileItemFactory.setSizeThreshold(1 * 1024 * 1024); // 1 MB
		/*
		 * Set the temporary directory to store the uploaded files of size above
		 * threshold.
		 */
		fileItemFactory.setRepository(tmpDir);

		ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
		try {
			/*
			 * Parse the request
			 */
			List items = uploadHandler.parseRequest(request);
			Iterator itr = items.iterator();
			while (itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				/*
				 * Handle Form Fields.
				 */
				if (item.isFormField()) {
					out.println("File Name = " + item.getFieldName()
							+ ", Value = " + item.getString());
				} else {
					// Handle Uploaded files.
					out.println("Field Name = " + item.getFieldName()
							+ ", File Name = " + item.getName()
							+ ", Content type = " + item.getContentType()
							+ ", File Size = " + item.getSize());
					/*
					 * Write file to the ultimate location.
					 */
					File file = new File(destinationDir, item.getName());
					item.write(file);
				}
				out.close();
			}
		} catch (FileUploadException ex) {
			log("Error encountered while parsing the request", ex);
		} catch (Exception ex) {
			log("Error encountered while uploading file", ex);
		}

	}

}


You can download code from
SVN Link for working code