Steps to develop download servlet:-
1.Set the header of HttpServlet Response i.e.
response.setHeader("content-disposition","attachment;filename="+fname); where fname denotes the name of file to be downloaded on browser.
2.Set the ContentType of response i.e.
response.setContentType("application/octet-stream");
3.Obtain the byte oriented output stream from the response i.e.
OutputStream out=response.getOutputStream();
Servlet code is given as under:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class DownloadServlet extends HttpServlet
{
public void service(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException
{
try
{
String name=request.getParameter("name");
response.setHeader("content-disposition","attachment;filename="+name);
response.setContentType("application/octet-stream");
OutputStream out=response.getOutputStream();
String downpath=this.getServletConfig().getServletContext().getRealPath("")+"\\"+"upload"+"\\"+name;
FileInputStream fin=new FileInputStream(downpath);
byte b[]=new byte[fin.available()];
fin.read(b);
out.write(b);
out.close();
fin.close();
}catch(Exception e){System.out.println(e);}
}
}
upload is name of a folder parallel to WEB-INF in which files to be downloaded are stored.
Click here to get working example
0 comments:
Post a Comment