JSP Tutorial on JSP File Uploading

in this chapter, we will discuss file uploading in jsp. a jsp can be used with an html form tag to allow users to upload files to the server. an uploaded file can be a text file or a binary or an image file or just any document.

creating a file upload form

let us now understand how to create a file upload form. the following html code creates an uploader form. following are the important points to be noted down −

  • the form method attribute should be set to post method and get method can not be used.

  • the form enctype attribute should be set to multipart/form-data.

  • the form action attribute should be set to a jsp file which would handle file uploading at backend server. following example is using uploadfile.jsp program file to upload file.

  • to upload a single file you should use a single <input .../> tag with attribute type = "file". to allow multiple files uploading, include more than one input tag with different values for the name attribute. the browser associates a browse button with each of them.

<html>
   <head>
      <title>file uploading form</title>
   </head>
   
   <body>
      <h3>file upload:</h3>
      select a file to upload: <br />
      <form action = "uploadservlet" method = "post"
         enctype = "multipart/form-data">
         <input type = "file" name = "file" size = "50" />
         <br />
         <input type = "submit" value = "upload file" />
      </form>
   </body>
   
</html>

this will display the following result. you can now select a file from the local pc and when the user clicks "upload file", the form gets submitted along with the selected file −

file upload

select a file to upload −



note − above form is just dummy form and would not work, you should try above code at your machine to make it work.

writing backend jsp script

let us now define a location where the uploaded files will be stored. you can hard code this in your program or this directory name can also be added using an external configuration such as a context-param element in web.xml as follows −

<web-app>
....
<context-param> 
   <description>location to store uploaded file</description> 
   <param-name>file-upload</param-name> 
   <param-value>
      c:\apache-tomcat-5.5.29\webapps\data\
   </param-value> 
</context-param>
....
</web-app>

following is the source code for uploadfile.jsp. this can handle uploading of multiple files at a time. let us now consider the following before proceeding with the uploading of files.

  • the following example depends on fileupload; make sure you have the latest version of commons-fileupload.x.x.jar file in your classpath. you can download it from https://commons.apache.org/fileupload/.

  • fileupload depends on commons io; make sure you have the latest version of commons-io-x.x.jar file in your classpath. you can download it from https://commons.apache.org/io/.

  • while testing the following example, you should upload a file which is of less size than maxfilesize otherwise the file will not be uploaded.

  • make sure you have created directories c:\temp and c:\apache-tomcat5.5.29\webapps\data well in advance.

<%@ 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.*" %>

<%
   file file ;
   int maxfilesize = 5000 * 1024;
   int maxmemsize = 5000 * 1024;
   servletcontext context = pagecontext.getservletcontext();
   string filepath = context.getinitparameter("file-upload");

   // verify the content type
   string contenttype = request.getcontenttype();
   
   if ((contenttype.indexof("multipart/form-data") >= 0)) {
      diskfileitemfactory factory = new diskfileitemfactory();
      // maximum size that will be stored in memory
      factory.setsizethreshold(maxmemsize);
      
      // location to save data that is larger than maxmemsize.
      factory.setrepository(new file("c:\\temp"));

      // create a new file upload handler
      servletfileupload upload = new servletfileupload(factory);
      
      // maximum file size to be uploaded.
      upload.setsizemax( maxfilesize );
      
      try { 
         // parse the request to get file items.
         list fileitems = upload.parserequest(request);

         // process the uploaded file items
         iterator i = fileitems.iterator();

         out.println("<html>");
         out.println("<head>");
         out.println("<title>jsp file upload</title>");  
         out.println("</head>");
         out.println("<body>");
         
         while ( i.hasnext () ) {
            fileitem fi = (fileitem)i.next();
            if ( !fi.isformfield () ) {
               // get the uploaded file parameters
               string fieldname = fi.getfieldname();
               string filename = fi.getname();
               boolean isinmemory = fi.isinmemory();
               long sizeinbytes = fi.getsize();
            
               // write the file
               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 + "<br>");
            }
         }
         out.println("</body>");
         out.println("</html>");
      } catch(exception ex) {
         system.out.println(ex);
      }
   } else {
      out.println("<html>");
      out.println("<head>");
      out.println("<title>servlet upload</title>");  
      out.println("</head>");
      out.println("<body>");
      out.println("<p>no file uploaded</p>"); 
      out.println("</body>");
      out.println("</html>");
   }
%>

now try to upload files using the html form which you created above. when you try http://localhost:8080/uploadfile.htm, it will display the following result. this will help you upload any file from your local machine.

file upload

select a file to upload −


if your jsp script works fine, your file should be uploaded in c:\apache-tomcat5.5.29\webapps\data\ directory.