logo

Example Of Uploading File To The Server In Servlet


Show

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.

Index.html

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

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.

UploadServlet.java

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 {  
  
response.setContentType("text/html");  
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.

<web-app>  
  
<servlet>  
<servlet-name>UploadServlet</servlet-name>  
<servlet-class>UploadServlet</servlet-class>  
</servlet>  
  
<servlet-mapping>  
<servlet-name>UploadServlet</servlet-name>  
<url-pattern>/go</url-pattern>  
</servlet-mapping>  
  
</web-app>  

download this example (developed without IDE)

download this example (developed using Myeclipse IDE)

download this example (developed using Netbeans IDE)