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