NOTICE

Adfly Links not working Find Direct Links HERE

How to create a Force Download link for pdf file in JSP
















Create 2 Files 

 DownloadPage.JSP code :-


<a href='downloadPdf.jsp?file=FILE.pdf' >Download PDF File</a>

downloadPdf.JSP code :-




<%@ page import="java.util.*,java.io.*" %>               
          
<!--contents of download.jsp-->
<!--Assumes that file name is in the request objects query Parameter -->
<%
 //read the file name.
 
    //out.print("D:/Inder Folder/data/PDL Back UP/30 july/reverted OLD/Copy of PanjabDigi 8 june/PanjabDigi OLD WITH ADV SEARCH/web/webuser/exhibitions/" + request.getParameter("file") );

%>

<%
 File f = new File ("E:/PDLDataServer/Downloads/PdfFiles/" + request.getParameter("file") );
 //set the content type(can be excel/word/powerpoint etc..)
 response.setContentType ("application/pdf");
 //set the header and also the Name by which user will be prompted to save
 response.setHeader ("Content-Disposition", "attachment; filename=\""+request.getParameter("file")+"\"");
 
 //get the file name
 String name = f.getName().substring(f.getName().lastIndexOf("/") + 1,f.getName().length());
 //OPen an input stream to the file and post the file contents thru the 
 //servlet output stream to the client m/c
 
  InputStream in = new FileInputStream(f);
  ServletOutputStream outs = response.getOutputStream();
  
  
  int bit = 256;
  int i = 0;
  try {
   while ((bit) >= 0) {
    bit = in.read();
    outs.write(bit);
   }
   //System.out.println("" +bit);
  } catch (IOException ioe) {
   ioe.printStackTrace(System.out);
  }
//  System.out.println( "n" + i + " bytes sent.");
//  System.out.println( "n" + f.length() + " bytes sent.");
  outs.flush();
  outs.close();
  in.close(); 

%>


2 comments :

Feel free to leave comment if you like above widget, have any questions or just say Hi! :)