File Uploading in Servlets

Introduction

We can upload the file on the server using Servlet with HTML tag. The Servlet program uploads the files into a directory in the Servlet. The method must be post and encrypt must be multipart/form-data for uploading the file.

Example : Uploading the file

//index.html

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

FileUploadApp.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.oreilly.servlet.MultipartRequest;  
public class FileUploadApp extends HttpServlet
{
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
    {
        response.setContentType("text/html");
        PrintWriter pw = response.getWriter();
        MultipartRequest multi = new MultipartRequest(request, "F:\Test\SurenDra");
        pw.println("File uploaded");
        pw.close();
    }
}

//web.xml

<web-app>  
     <servlet>  
         <servlet-name>FileUploadApp</servlet-name>  
         <servlet-class>FileUploadApp</servlet-class>  
     </servlet>  
     <servlet-mapping>  
         <servlet-name>FileUploadApp</servlet-name>  
         <url-pattern>/upload</url-pattern>  
     </servlet-mapping>  
</web-app>