{"id":246,"date":"2007-09-19T00:00:00","date_gmt":"2007-09-19T00:00:00","guid":{"rendered":"http:\/\/www.strongd.net\/?p=246"},"modified":"2007-09-19T00:00:00","modified_gmt":"2007-09-19T00:00:00","slug":"Handling Form-based File Upload with Java Servlet or JSP","status":"publish","type":"post","link":"https:\/\/www.strongd.net\/?p=246","title":{"rendered":"Handling Form-based File Upload with Java Servlet or JSP"},"content":{"rendered":"<p><P><SPAN class=mainText>Unlike PHP, Java Servlet and JSP do not have build-in mechanisms for handling form-based file uploads. One solution to this problem is to implement a function yourself to extract uploaded files contained in an HTTP request. However, a better choice is to make use of a third-party library that can help us handle file uploads.<\/SPAN><\/P><br \/><P><SPAN class=mainText>One robust library available is the Apache Jakarta Commons FileUpload package. It is open-source and can be downloaded free of charge over the Internet. We will demonstrate how to use the Apache Jakarta Commons FileUpload package to extract uploaded files submitted from a form. The techniques are the same for HTML and XHTML. If you are not familiar with JSP or Java Servlet, you may want to read some introductory tutorials before going through this section.<\/SPAN><\/P><br \/><P><SPAN class=mainText>At the time of writing, the most up-to-date version of the Apache Jakarta Commons FileUpload library is 1.1.1. So, we assume you are using Commons FileUpload 1.1.1 in this tutorial. For other versions of Commons FileUpload, the procedures may be slightly different but the principle is the same.<\/SPAN><\/P><br \/><P><BR><\/P><br \/><H2><A name=\"4.1.Downloading the Apache Jakarta Commons FileUpload and Commons IO Libraries|outline\"><\/A>Downloading the Apache Jakarta Commons FileUpload and Commons IO Libraries<\/H2><br \/><P><SPAN class=mainText>To download the Apache Jakarta Commons FileUpload library, go to the home page of the <A href=\"http:\/\/jakarta.apache.org\/commons\/fileupload\/\">Apache Jakarta Commons FileUpload project<\/A> and navigate to the download section. The binaries are available in two file formats: zip format and tar-gzip format. Download either one of them and uncompress the file. Then go to the home page of the <A href=\"http:\/\/jakarta.apache.org\/commons\/io\/\">Apache Jakarta Commons IO project<\/A> and repeat the same steps. We need the Commons IO library since Commons FileUpload uses it internally. Now you have two JAR files, &#8220;commons-fileupload-<I>version<\/I>.jar&#8221; and &#8220;commons-io-<I>version<\/I>.jar&#8221;, where <I>version<\/I> is the version number. At the time of writing, the latest version of the Commons FileUpload library and that of the Commons IO library are 1.1.1 and 1.2 respectively. So, the JAR files we obtain are &#8220;commons-fileupload-1.1.1.jar&#8221; and &#8220;commons-io-1.2.jar&#8221;.<\/SPAN><\/P><br \/><P><BR><\/P><br \/><H2><A name=\"4.2.Installing Apache Jakarta Commons FileUpload and Commons IO into a Servlet\/JSP Container Like Tomcat|outline\"><\/A>Installing Apache Jakarta Commons FileUpload and Commons IO into a Servlet\/JSP Container Like Tomcat<\/H2><br \/><P><SPAN class=mainText>Next, we need to install the Apache Jakarta Commons FileUpload library and the Apache Jakarta Commons IO library into a Servlet\/JSP container such as Apache Tomcat. To do this, copy the JAR files &#8220;commons-fileupload-1.1.1.jar&#8221; and &#8220;commons-io-1.2.jar&#8221; to the \/WEB-INF\/lib\/ directory in the document root of your web application.<\/SPAN><\/P><br \/><P><SPAN class=mainText>Note that JAR libraries stored in \/WEB-INF\/lib\/ will be available to the containing web application only. If you want to share the libraries among all web applications installed in Tomcat (suppose you are using Tomcat 5 or Tomcat 4), the JAR files should be copied to the <I>$CATALINA_HOME<\/I>\/shared\/lib\/ directory, where <I>$CATALINA_HOME<\/I> is the root of your Tomcat installation.<\/SPAN><\/P><br \/><P><BR><\/P><br \/><H2><A name=\"4.3.Checking If an HTTP Request is Encoded in Multipart Format|outline\"><\/A>Checking If an HTTP Request is Encoded in Multipart Format<\/H2><br \/><P><SPAN class=mainText>Now that you have installed the Apache Jakarta Commons FileUpload library, you can start writing the code. First, we have to make sure the HTTP request is encoded in multipart format. This can be done using the static method <I>isMultipartContent()<\/I> of the <I>ServletFileUpload<\/I> class of the <I>org.apache.commons.fileupload.servlet<\/I> package:<\/SPAN><\/P><br \/><P><BR><\/P><br \/><P><SPAN class=codeText>if (ServletFileUpload.isMultipartContent(request)){<BR>&nbsp;&nbsp;\/\/ Parse the HTTP request&#8230;<BR>}<\/SPAN><\/P><br \/><P><BR><\/P><br \/><P><SPAN class=mainText>In the above Java code snippet, <I>request<\/I> is a <I>javax.servlet.http.HttpServletRequest<\/I> object that encapsulates the HTTP request. It should be very familiar to you if you know Java Servlet or JSP.<\/SPAN><\/P><br \/><P><BR><\/P><br \/><H2><A name=\"4.4.Parsing Form Data with Java Servlet \/ JSP|outline\"><\/A>Parsing Form Data with Java Servlet \/ JSP<\/H2><br \/><P><SPAN class=mainText>Second, we will parse the form data contained in the HTTP request. Parsing the form data is very straightforward with the Apache Jakarta Commons FileUpload library:<\/SPAN><\/P><br \/><P><BR><\/P><br \/><P><SPAN class=codeText>ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());<BR>List fileItemsList = servletFileUpload.parseRequest(request);<\/SPAN><\/P><br \/><P><BR><\/P><br \/><P><SPAN class=mainText>(In the above Java code snippet, <I>DiskFileItemFactory<\/I> is a class contained in the <I>org.apache.commons.fileupload.disk<\/I> package and <I>List<\/I> is an interface contained in the <I>java.util<\/I> package.)<\/SPAN><\/P><br \/><P><SPAN class=mainText>If everything works fine, <I>fileItemsList<\/I> will contain a list of file items that are instances of <I>FileItem<\/I> of the <I>org.apache.commons.fileupload<\/I> package. A file item may contain an uploaded file or a simple name-value pair of a form field. (More details about <I>FileItem<\/I> will be provided later.)<\/SPAN><\/P><br \/><P><SPAN class=mainText>By default, the <I>ServletFileUpload<\/I> instance created by the above Java code uses the following values when parsing the HTTP request:<\/SPAN><\/P><br \/><UL><br \/><LI><br \/><P><SPAN class=mainText>Size threshold = 10,240 bytes. If the size of a file item is smaller than the size threshold, it will be stored in the memory. Otherwise it will be stored in a temporary file on disk.<\/SPAN><\/P><br \/><LI><br \/><P><SPAN class=mainText>Maximum HTTP request body size = -1, which means the server will accept HTTP request bodies of any size.<\/SPAN><\/P><br \/><LI><br \/><P><SPAN class=mainText>Repository = System default temp directory, whose value can be found by the Java code <I>System.getProperty(&#8220;java.io.tmpdir&#8221;)<\/I>. Temporary files will be stored there.<\/SPAN><\/P><\/LI><\/UL><br \/><P><SPAN class=mainText>If you do not like the default settings, you can change them using the methods <I>setSizeThreshold()<\/I> and <I>setRespository()<\/I> of the <I>DiskFileItemFactory<\/I> class and the <I>setSizeMax()<\/I> method of the <I>ServletFileUpload<\/I> class, like this:<\/SPAN><\/P><br \/><P><BR><\/P><br \/><P><SPAN class=codeText>DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();<BR>diskFileItemFactory.setSizeThreshold(40960); \/* the unit is bytes *\/<BR><BR>File repositoryPath = new File(&#8220;\/temp&#8221;);<BR>diskFileItemFactory.setRepository(repositoryPath);<BR><BR>ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);<BR>servletFileUpload.setSizeMax(81920); \/* the unit is bytes *\/<\/SPAN><\/P><br \/><P><BR><\/P><br \/><P><SPAN class=mainText>(In the above Java code snippet, <I>File<\/I> is a class of the <I>java.io<\/I> package.)<\/SPAN><\/P><br \/><P><SPAN class=mainText>If the size of the HTTP request body exceeds the maximum you set, the <I>SizeLimitExceededException<\/I> exception (fully qualified name: <I>org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException<\/I>) will be thrown when you call the <I>parseRequest()<\/I> method:<\/SPAN><\/P><br \/><P><BR><\/P><br \/><P><SPAN class=codeText>try {<BR>&nbsp;&nbsp;List fileItemsList = servletFileUpload.parseRequest(request);<BR>&nbsp;&nbsp;\/* Process file items&#8230; *\/<BR>}<BR>catch (SizeLimitExceededException ex) {<BR>&nbsp;&nbsp;\/* The size of the HTTP request body exceeds the limit *\/<BR>}<\/SPAN><\/P><br \/><P><BR><\/P><br \/><H2><A name=\"4.5.Iterating through File Items|outline\"><\/A>Iterating through File Items<\/H2><br \/><DIV><br \/><P><SPAN class=mainText>Third, we will iterate through the file items and process each of them. The <I>isFormField()<\/I> method of the <I>FileItem<\/I> interface is used to determine whether a file item contains a simple name-value pair of a form field or an uploaded file:<\/SPAN><\/P><br \/><P><BR><\/P><br \/><P><SPAN class=codeText>Iterator it = fileItemsList.iterator();<BR>while (it.hasNext()){<BR>&nbsp;&nbsp;FileItem fileItem = (FileItem)it.next();<BR>&nbsp;&nbsp;if (<B>fileItem.isFormField()<\/B>){<BR>&nbsp;&nbsp;&nbsp;&nbsp;\/* The file item contains a simple name-value pair of a form field *\/<BR>&nbsp;&nbsp;}<BR>&nbsp;&nbsp;else{<BR>&nbsp;&nbsp;&nbsp;&nbsp;\/* The file item contains an uploaded file *\/<BR>&nbsp;&nbsp;}<BR>}<\/SPAN><\/P><br \/><P><BR><\/P><br \/><P><SPAN class=mainText>(In the above Java code snippet, <I>Iterator<\/I> is an interface in the <I>java.util<\/I> package and <I>FileItem<\/I> is an interface in the <I>org.apache.commons.fileupload<\/I> package.)<\/SPAN><\/P><\/DIV><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Unlike PHP, Java Servlet and JSP do not have build-in mechanisms for handling form-based file uploads. One solution to this problem is to implement a function yourself to extract uploaded files contained in an HTTP request. However, a better choice is to make use of a third-party library that can help us handle file uploads.One &hellip; <a href=\"https:\/\/www.strongd.net\/?p=246\" class=\"more-link\">Continue reading <span class=\"screen-reader-text\">Handling Form-based File Upload with Java Servlet or JSP<\/span><\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[],"tags":[],"class_list":["post-246","post","type-post","status-publish","format-standard","hentry"],"_links":{"self":[{"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/posts\/246","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.strongd.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=246"}],"version-history":[{"count":0,"href":"https:\/\/www.strongd.net\/index.php?rest_route=\/wp\/v2\/posts\/246\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.strongd.net\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=246"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.strongd.net\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=246"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.strongd.net\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=246"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}