Uploading File

This aritcle shows how to save a file that is uploaded from client using File control of HTML.

Java Servlet API doesn't provide any method to handle file upload. So, we have to depend on a library provided by third parties.

This article uses Commons Fileupload library provided by Apache. This can be downloaded from apache website ( jakarta.apache.org). This library is also part of Tomcat 5.0 and Jakarta Struts 1.1.

The following examples shows how to create an HTML form to upload file to a JSP. Then JSP saves the uploaded file in the filename given by client.

HTML Form

The following is the html form that takes file to be uploaded and filename using which the file is to be saved on the server.
<form  action="upload.jsp"  method="post"  enctype="multipart/form-data">
Select File <input type="file" name="file1">
<p>
Select Filename <input type="text" size="20" name="filename">
<p>
<input type=submit value="Upload">
</form>

The following is the JSP used to take file uploaded from client and save it on the server.

<%@page import="org.apache.commons.fileupload.*,java.util.*,java.io.*"%>

<%
   // JSP to handle  uploading
   
   
   // Create a new file upload handler 
   DiskFileUpload upload = new DiskFileUpload();
   
   // parse request
   List items = upload.parseRequest(request);
   
   // get uploaded file 
   FileItem  file = (FileItem) items.get(0);
   String source = file.getName();
   
   // get taget filename
   FileItem  name = (FileItem) items.get(1);
   String  target = name.getString();
     
    
   File outfile = new File("c:\\tomcat\\temp\\" +  target);
   file.write(outfile);
   
   out.println("Upload Is Successful!");
   
%>

Keep Learning,

P.Srikanth