Since Servlet 3.0 (JavaEE 6), Servlet 3.0 supports two additional HttpServletRequest methods:
Collection<Part> getParts()
Part getPart(String name)
With this, you don’t need other library anymore to perform some file uploads.
To set the upload properties, you can use the @MultipartConfig annotation. The @MultipartConfig annotation indicates that the servlet expects requests to be made using the multipart/form-data MIME type. Here’s an example:
@MultipartConfig(location="/tmp", fileSizeThreshold=1024*1024,
maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5)
Instead of using the @MultipartConfig annotation to hard-code these attributes in your file upload servlet, you could add the following as a child element of the servlet configuration element in the web.xml file:
<multipart-config>
<location>/tmp</location>
<max-file-size>20848820</max-file-size>
<max-request-size>418018841</max-request-size>
<file-size-threshold>1048576</file-size-threshold>
</multipart-config>
But if you want to set dynamically your upload settings (via properties for example) from your java code, you’re stuck. Using the Dynamic servlet registration as described in my previous post, you can instanciate the configuration object and set whatever you want:
package org.jerometambo.dynamicservletinitializer.servlet;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.ServletRegistration.Dynamic;
/**
* Servlets initialization.
*/
public class DynamicServletInitializer implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
final int size = Parameters.UPLOAD_SIZE_LIMIT * 1024; //from wherever you want
Dynamic registered = servletContextEvent.getServletContext().addServlet("HelloWorld", HelloWorld.class);
registered.addMapping("/HelloWorld");
registered.setMultipartConfig(new MultipartConfigElement(Parameters.UPLOAD_TEMP_DIR, size, size, size));
}
public void contextDestroyed(ServletContextEvent sce) {
}
}
You can find an example on my github: https://github.com/jerometambo/dynamicservletinitializer on the uploadConfigFromProperties branch.
You can find an utils lib to deal with File uploads on my github: https://github.com/jerometambo/javaeeuploadutils on the master branch.
Useful links:
Tchou !