Friday, 2 October 2015

Example of uploading file to the server in servlet

Example of uploading file to the server in servlet

Here, we will learn how to upload file to the server. For uploading a file to the server, method must be post and enctype must be multipart/form-data in html file. For Example:

index.html
  1. <html>  
  2. <body>  
  3. <form action="go" method="post" enctype="multipart/form-data">  
  4. Select File:<input type="file" name="fname"/><br/>  
  5. <input type="submit" value="upload"/>  
  6. </form>  
  7. </body>  
  8. </html>  

Example of uploading file to the server in servlet

Now, for uploading a file to the server, there can be various ways. But, I am going to use MultipartRequest class provided by oreilly. For using this class you must have cos.jar file. If you will download this example, we will the cos.jar file alongwith code.

UploadServlet.java
  1. import java.io.*;  
  2. import javax.servlet.ServletException;  
  3. import javax.servlet.http.*;  
  4. import com.oreilly.servlet.MultipartRequest;  
  5.   
  6. public class UploadServlet extends HttpServlet {  
  7.   
  8. public void doPost(HttpServletRequest request, HttpServletResponse response)  
  9.     throws ServletException, IOException {  
  10.   
  11. response.setContentType("text/html");  
  12. PrintWriter out = response.getWriter();  
  13.           
  14. MultipartRequest m=new MultipartRequest(request,"d:/new");  
  15. out.print("successfully uploaded");  
  16. }  
  17. }  
There are two arguments passed in MultipartRequest class constructor, first one is HttpServletRequest object and second one is String object (for location). Here I am supposing that you have new folder in D driver.

web.xml file
This configuration file provides information about the servlet.
  1. <web-app>  
  2.   
  3. <servlet>  
  4. <servlet-name>UploadServlet</servlet-name>  
  5. <servlet-class>UploadServlet</servlet-class>  
  6. </servlet>  
  7.   
  8. <servlet-mapping>  
  9. <servlet-name>UploadServlet</servlet-name>  
  10. <url-pattern>/go</url-pattern>  
  11. </servlet-mapping>  
  12.   
  13. </web-app>  

No comments:

Post a Comment