Skip to content

Instantly share code, notes, and snippets.

@preslavrachev
Created May 15, 2013 08:08
Show Gist options
  • Save preslavrachev/5582378 to your computer and use it in GitHub Desktop.
Save preslavrachev/5582378 to your computer and use it in GitHub Desktop.
Handling an Uploadify file upload with a servlet (thanks to http://stackoverflow.com/a/2273711/1107412)
<!DOCTYPE html>
<html lang="en">
<head>
<title>Uploadify test</title>
<script src="uploadify/jquery-1.3.2.min.js"></script>
<script src="uploadify/swfobject.js"></script>
<script src="uploadify/jquery.uploadify.v2.1.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#uploadify').uploadify({
'uploader': 'uploadify/uploadify.swf',
'script': 'uploadServlet',
'folder': '/uploads',
'cancelImg': 'uploadify/cancel.png'
});
$('#upload').click(function() {
$('#uploadify').uploadifyUpload();
return false;
});
});
</script>
</head>
<body>
<input id="uploadify" type="file">
<a id="upload" href="#">Upload</a>
</body>
</html>
package com.example;
import java.io.IOException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
System.out.println("UploadServlet invoked. Here are all uploaded files: ");
try {
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
System.out.println("Name: " + item.getName());
System.out.println("Size: " + item.getSize());
System.out.println("Type: " + item.getContentType());
}
}
} catch (Exception e) {
throw new ServletException(e);
}
}
}
<servlet>
<servlet-name>uploadServlet</servlet-name>
<servlet-class>com.example.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>uploadServlet</servlet-name>
<url-pattern>/uploadServlet</url-pattern>
</servlet-mapping>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment