YUI file upload with jsp backend

For last two weeks I was working on some user interface logic and happened to use Yahoo UI library (YUI). The task was to upload an image using Ajax. Since I was new to YUI, I was looking here and there over the net for some references. There were some good ones but thats for PHP back-ends, but mine was a jsp back-end and i didn’t know how to read the object thrown out from the YUI side.

with some more digging I came across nice file handling library in Apache commons (Commons File Upload) and took use of it to do the task. the code is as follows.



YUI File UploadS
http://[PATH_TO_YUI]/yahoo-dom-event/yahoo-dom-event.js
http://[PATH_TO_YUI]/connection/connection-min.js

function init(){
  var onUploadButtonClick = function(e){
    //the second argument of setForm is crucial,
    //which tells Connection Manager this is a file upload form
    YAHOO.util.Connect.setForm('testForm', true);

    var uploadHandler = {
      upload: function(o) {
        alert(o.responseText);
      }
    };
  YAHOO.util.Connect.asyncRequest('POST', 'upload.php', uploadHandler);
  };
  YAHOO.util.Event.on('uploadButton', 'click', onUploadButtonClick);
}

YAHOO.util.Event.on(window, 'load', init);














I took the above code segment directly from a YUI file upload tutorial hence the credit goes to the author. The jsp back-end using apache commons file upload is as follows.

if (ServletFileUpload.isMultipartContent(request)) {
	FileItemFactory factory = new DiskFileItemFactory();

	ServletFileUpload servletFileUpload = new ServletFileUpload(
					factory);
	List fileItemsList = servletFileUpload
					.parseRequest(request);

	String optionalFileName = "";
	FileItem fileItem = null;

	Iterator it = fileItemsList.iterator();

	while (it.hasNext()) {
		FileItem item = (FileItem) it.next();
		if (item.isFormField()) {
		//Other form values
			if (item.getFieldName().equals("test"))
				gName = item.getString();
			if (item.getFieldName().equals("test-2"))
				gUrl = item.getString();
			if (item.getFieldName().equals("test-3"))
				gDesc = item.getString();
		} else {
			contentType = item.getContentType();
			itemSizeInBytes = item.getSize();
			//any operation with the file goes here
		}

	}
			
}

So thats how it goes 🙂

Advertisement

One thought on “YUI file upload with jsp backend”

  1. Thanks ! I was thinking on similar lines, however your article helped me to check and confirm that we seem to be headed the right way.

    Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s