Wednesday, April 1, 2020

Download files from server using JSP

If the file is dynamic i.e. a JSP file then:

//in the html file
<a href="download.jsp">download the jsp file</a> 

// the download.jsp file
  1. <%    
  2.   String filename = "home.jsp";   
  3.   String filepath = "e:\\";   
  4.   response.setContentType("APPLICATION/OCTET-STREAM");   
  5.   response.setHeader("Content-Disposition","attachment; filename=\"" + filename + "\"");   
  6.   
  7.   java.io.FileInputStream fileInputStream=new java.io.FileInputStream(filepath + filename);  
  8.             
  9.   int i;   
  10.   while ((i=fileInputStream.read()) != -1) {  
  11.     out.write(i);   
  12.   }   
  13.   fileInputStream.close();   
  14. %>   

Source: javatpoint https://www.javatpoint.com/downloading-file-from-the-server-in-jsp

But if the file is static e.g. a txt file the:

It can be done in a much simpler way :

If the resource is static, just put it in the public webcontent (there where your JSP/HTML/CSS/JS/etc files also are) and include a link to it in your JSP.

<a href="file.txt">download</a>

Source: stackoverflow https://stackoverflow.com/questions/4005873/using-jsp-to-download-a-file

No comments:

Post a Comment

Sacred Thought

5 May 2024 Hari Om Verse 50-51, chapter two:  In this chapter two Shree krishna explains a simple way of living. Free from desires and void ...