Code »

Spark Java File Upload

spark java is a micro framework inspired by sinatra for java. It’s a really cool substitute for spring mvc which is a drag to because it takes so much time to boot the framework.
I’ve been giving spark a go on a few projects (see: pads ) and I am quite pleased with the results. The new version also supports java 8 and has a lot of improvements over the 1.1.1 version.
A problem that I came across using spark was during file uploads. Spark uses an embedded jetty server and the servlet 3.0 spec which requires @MultipartConfig on servlets that handle file uploads. Since spark is using handlers and you dreally don’t want to configure servlets and a web.xml fileuploading needs a work around which is rather simple. On the handler that is going to process the file upload just add these lines:

 public Object handle(Request request, Response response) {
   MultipartConfigElement multipartConfigElement = new MultipartConfigElement("/tmp");
   request.raw().setAttribute("org.eclipse.multipartConfig", multipartConfigElement);
   ....
   Part file = request.raw().getPart("file"); //file is name of the upload form

the parameter to MultiparConfig is the location for the temporary uploaded file.

edit SideBar

Page last modified on August 26, 2016, at 04:35 PM - Powered by PmWiki

^