JAVA Servlet Program to Download a file and display it on the screen
Posted by MohammadYusuf
Last Updated: October 28, 2016

DownloadServlet.java file

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class DownloadServlet extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res)
 throws ServletException, IOException
{
res.setContentType("application/msword");
res.setHeader("Content-Disposition","attachment;filename=hello.docx");
ServletOutputStream output=res.getOutputStream();
FileInputStream file=new FileInputStream("E:\\hello.docx");
int c=0;
while((c=file.read())!=-1)
{
output.write(c);
}
output.flush();
file.close();
output.close();
}
}

 

 

Download.html file

<html>
<head>
<title></title>
</head>
<body>
<a href="http://localhost:8080/examples/servlet/
DownloadServlet"> click here to know about SQL
</a>
</h1>
</body>
</html>