Example Of Uploading File To The Server In Servlet


Here we will study how to upload the file to the server. The method must be post and enctype must be multipart or form data in HTML file, For uploading a file to the server.


<form action="go" method="post" enctype="multipart/form-data">  
Select File:<input type="file" name="fname"/><br/>  
<input type="submit" value="upload"/>  

Example of Updating File to the Server in Servlet

Now, for uploading a file to the server, there are many different ways. But here we are going to use the MultipartRequest class provided by oreily. To use this class you must have a cos.jar file. If you download this example, we are providing the cos.jar file along with the code.


import java.io.*;  
import javax.servlet.ServletException;  
import javax.servlet.http.*;  
import com.oreilly.servlet.MultipartRequest;  
public class UploadServlet extends HttpServlet {  
public void doPost(HttpServletRequest request, HttpServletResponse response)  
    throws ServletException, IOException {  
PrintWriter out = response.getWriter();  
MultipartRequest m=new MultipartRequest(request,"d:/new");  
out.print("successfully uploaded");  

Two main arguments passed in the MultipartRequest class Constructor, First one is the HttpServletRequest object and the second one is String object (for location). Now, I am presuming that you have a new folder in the D drive.

Web.xml file

This Configuration File Provides the information about the Servlet.


download this example (developed without IDE)

download this example (developed using Myeclipse IDE)

download this example (developed using Netbeans IDE)