Saturday, 12 October 2013

File Download Using Servlets

HTML Code:

<html>
<body>
<form name="fileUploadForm" method="POST" action="sdd2">
<input type="submit" value="Download"/>
</form>
</body>

</html>

Web.xml:

<web-app>
 <servlet>
  <servlet-name>sdd2</servlet-name>
  <servlet-class>com.iton.DownloadServlet</servlet-class>

  </servlet>

<servlet-mapping>
  <servlet-name>sdd2</servlet-name>
  <url-pattern>/sdd2</url-pattern>
  </servlet-mapping>

</web-app>

Servlet Code:

import java.io.FileInputStream;
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;

public class DownloadServlet extends HttpServlet
{
  public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    response.setContentType("text/html");
    
    PrintWriter out = response.getWriter();
    
    String filename = "Page1.jpg";
    
     //Give the path where the files are available in server
    //We can give our project folder in the Server
    String filepath = "C:/myfiles/";
    
    response.setContentType("APPLICATION/OCTET-STREAM");
    
    response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");

    FileInputStream fis = new FileInputStream(filepath + filename);
    
    int i;
    
    while ((i = fis.read()) != -1)
    {
      out.write(i);
    }
    fis.close();
    out.close();
  }

}

Output:




No comments:

Post a Comment