File upload using java servlet and Tomcat
August 9, 2014 . Comments
Tags: java, tomcat, JVM
As part of this blog we will look at how to upload and process a file using java Servlet API. I will not be using the Apache File-Upload API.
When defining your servlet determine a folder where you want the temporary file to be downloaded.
you can have the below MultipartConfig annotation as part of the Servlet class file like below.
@MultipartConfig(location="/tmp", fileSizeThreshold=-1L, maxFileSize=10*1024*1024, maxRequestSize=10*1024*1024)
public class FileUploaderServlet extends HttpServlet
{
or you can have it as a configuration as part of the web.xml file.
<multipart-config>
<location>/tmp</location>
<max-file-size>10485760</max-file-size>
<max-request-size>10489760</max-request-size>
<file-size-threshold>-1L</file-size-threshold>
</multipart-config>
If we are developing a general purpose file up-loader using the configuration in web.xml is the recommended approach. There are default values for all of the above which unlimited for all parameters . In my example my threshold is greater than the max-file-size so everything is instantaneous and in memory.
We are giving a sledge hammer here and the user can provide a large enough file to block the network. I would prefer the file size to be a max of 10 MB which is close to 10% of a Gigabit network traffic for a second. Any amount more than that will have the potential to create issues when more users are trying to download or upload contents to a server which is already processing other requests and potentially bring the server to a crawl for a few seconds.
Now for the code part
The below are the steps performed
I had introduced a new set of items IBranch and DataBranch these are the basic building blocks of banyan which is built on top of the ArrayMap interface. Banyan uses a modified version of the above class to upload contents of a csv into the data store. Banyan also supports other formats like JSON but not through this example.
Feel free to comment on the post but keep it clean and on topic.