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:




File Upload Using Servlets

Here We are using orelly related jar(cos.jar) for uploading files

Maven pom.xml for cos.jar

<dependency>
<groupId>servlets.com</groupId>
<artifactId>cos</artifactId>
<version>05Nov2002</version>
</dependency>

Link for Direct jar Download:

http://www.servlets.com/cos/


Html Code:

<html>
<body>
<form name="fileUploadForm" method="POST" action="fu3" enctype="multipart/form-data">
<input type="file" name="fileUpload"/>
<input type="submit" value="Upload"/>
</form>
</body>
</html>

Web.xml:

<web-app>
<servlet>
  <servlet-name>fu3</servlet-name>
  <servlet-class>com.iton.FileUploadUsingOreilly</servlet-class>
  </servlet>

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

</web-app>

Servlet Code:

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oreilly.servlet.MultipartRequest;

public class FileUploadUsingOreilly extends HttpServlet {

public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException {

PrintWriter out=response.getWriter();

//We have to create the folder myfiles in c driver
MultipartRequest m=new MultipartRequest(request,"c:/myfiles");

out.write("Successfully Uploaded");
}
}

Output: