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

How can I run a C++ program directly from Windows?

How-can-I-run-a-C-program-directly-from-Windows