SparkJava multipart/form-data fileUpload

Spark Framework is a simple and lightweight Java web framework built for rapid development. With Spark it’s possible to start a REST web server with a few lines of code.It is the Java porting of Sinatra: famous micro-framework written in Ruby.The purpose of this post is to explain how to work with Spark  for multipart/form-data fileUpload requirement.In different dev community I have seen people searching fix of fileUpload failure of SparkJava framework, so I thought to share the fix that I have encountered and fixed recently.


Spark.post("/files/upload/:userName", "multipart/form-data", new Route() {
			@Override
			public Object handle(Request request, Response response) {
				// process request
				String userID = request.params("userName");
				if (isValidUser(userID)) {
// These two lines work as fix.
MultipartConfigElement multipartConfigElement = new MultipartConfigElement("data/tmp");
request.raw().setAttribute("org.eclipse.jetty.multipartConfig", multipartConfigElement);

					Collection<Part> parts = null;
					try {
						parts = request.raw().getParts();
					} catch (IOException | ServletException e2) {
						// TODO Auto-generated catch block
						e2.printStackTrace();
					}
					for (Part part : parts) {
						System.out.println("Name:" + part.getName());
						System.out.println("Size: " + part.getSize());
						System.out.println("Filename:" + part.getSubmittedFileName());
					}
					String fName = null;
					Part file = null;
					try {
						file = request.raw().getPart("fileToBeUploaded");
						fName = request.raw().getPart("fileToBeUploaded").getSubmittedFileName();
					} catch (IOException | ServletException e1) {
						e1.printStackTrace();
					}