Published on Jul 25 2012 in Java

Some of you have troubles getting JSP upload functions in your code working. Here is upload code example that you can drop in to a JSP file in your webapp directory to quickly check if uploading works.

Common cause of problems is lack of write privileges in a directory where you are trying to upload to. It will upload to your current web app directory defined in filePath variable. The code uses commons-fileupload-1.2.2.jar and commons-io-2.4.jar in WEB-INF/lib to make it simple. Uploading code without these fileupload classes is bigger and not so easy readable. Here is the content of uploadtest.jsp.

<%@ page import="java.io.*,java.util.*, javax.servlet.*" %>
<%@ page import="javax.servlet.http.*" %>
<%@ page import="org.apache.commons.fileupload.*" %>
<%@ page import="org.apache.commons.fileupload.disk.*" %>
<%@ page import="org.apache.commons.fileupload.servlet.*" %>
<%@ page import="org.apache.commons.io.output.*" %>
<%
ServletContext context = pageContext.getServletContext();
String filePath = context.getRealPath(request.getContextPath()) + "/";
File file; 
int maxFileSize = 5000 * 1024; 
int maxMemSize = maxFileSize;
String contentType = request.getContentType();
    
if (contentType != null && (contentType.indexOf("multipart/form-data") >= 0)) {
     DiskFileItemFactory factory = new DiskFileItemFactory();
     factory.setSizeThreshold(maxMemSize); 
     factory.setRepository(new File("/tmp"));
     ServletFileUpload upload = new ServletFileUpload(factory);
     upload.setSizeMax(maxFileSize);
     try { 
       List fileItems = upload.parseRequest(request);
     Iterator i = fileItems.iterator();
     while (i.hasNext ()) {
       FileItem fi = (FileItem)i.next();
     if (!fi.isFormField ()) {
        String fieldName = fi.getFieldName();
      String fileName = fi.getName();
      if (fileName == "") out.println("You forgot to choose a file. <a href=''>Try again</a>");
      boolean isInMemory = fi.isInMemory();
      long sizeInBytes = fi.getSize();
     if( fileName.lastIndexOf("\\") >= 0 ) {
       file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
     } else { 
      file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")+1));
      }
     fi.write(file) ;
      out.println("Uploaded Filename: " + filePath + fileName + ", sizeInBytes = " + sizeInBytes + "<br/><a href=''>Upload again</a>");
      }
     }
     } catch(Exception ex) { System.out.println(ex); }
    } else {
     %> 
     <p>One needs commons-fileupload.x.x.jar and commons-io-x.x.jar fils in classpath (e.g. WEB-INF/lib).<br/> 
     You can download these from http://commons.apache.org/fileupload/ and http://commons.apache.org/io/</p>
     <h3>File Upload Test (uploaded file is to be saved under current context)</h3>
     <p><% out.println("Destination path: " + filePath); %></p>
     <form enctype="multipart/form-data" action="uploadtest.jsp" method="post"><table>
     <tr><td align="left">Select a file to upload:</td></tr>
     <tr><td align="left"><input type="file" name="filename" size="50"></td></tr>
     <tr><td align="left"><input type="submit" name="Submit" value="Upload">
     <input type="reset" name="Reset" value="Cancel"></td></tr>
     </table></form>
     <%  
} %>