You could create a file and -without storing it on the server- return it immediately as a downloadable file to the client.

This has the advantage that you don't need temporary storage on your server that might grow and keep growing unless you regularly clean it out.

Ofcourse if you wish to create an "archive" of old CSV files as a service to your clients then this is no real advantage. But most of the time the 'create/offer-for-download/throw-away' is the more interesting approach.

Here's some example code that may give you some idea:

1) the servlet (note: exception handling not shown)

public class CsvDownloadServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
    // fetch parameters from HTTP request

    String param = (String)request.getParameter("p");
    if (param == null)
    {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter p missing");
        return;
    }

    .... perhaps fetch more parameters ....

    .... build your CSV, using the parameter values ....

    String result = .... // suppose result is your generated CSV contents
    String filename = .... // choose a file name that your browser will suggest when saving the download

    // prepare writing the result to the client as a "downloadable" file

    response.setContentType("text/csv");
    response.setHeader("Content-disposition", "attachment; filename=\""+filename+"\"");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Expires", "-1");

    // actually send result bytes
    response.getOutputStream().write(result.getBytes());
}
}

2) configuration in WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      version="3.0"> 
     ....
    <servlet>
        <display-name>download</display-name>
        <servlet-name>download</servlet-name>
        <servlet-class>com.mypackage.CsvDownloadServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>download</servlet-name>
        <url-pattern>/download</url-pattern>
    </servlet-mapping>
    ....
</web-app>

3) the link on your page to trigger the download:

<a href="/myapp/download?p=myparamvalue">Click Here</a>

Here, /myapp is the "context-root" of your application, /download is configured in web.xml to be the location that triggers the CsvDownloadServlet code. p is an example parameter (see servlet code). If you have a form where the user fills in the parameter values, it could look like this:

 <form method='GET' action='/myapp/download'>
    Enter a value for parameter "p":
    <input id="p" type="text" size="10" name="p">
    <input type="submit" value="Generate and Download">
 </form>

This has the same effect as the previous <a> link, only the parameters are user supplied. As soon as the user clicks the submit button, the servlet code will be invoked and the CSV generation and subsequent download will start. Again, user input checking is not shown.

Answer from geert3 on Stack Overflow
🌐
Coderanch
coderanch.com › t › 293523 › java › Download-file-Server-client-machine
Download a file from Server to client machine (JSP forum at Coderanch)
October 13, 2016 - String filename = "C:\\folder name where you save file\\filename"; response.setContentType("application/octet-stream"); String disHeader = "Attachment; Filename=\"filename\""; response.setHeader("Content-Disposition", disHeader); File fileToDownload = new File(filename); InputStream in = null; ServletOutputStream outs = response.getOutputStream(); try { in = new BufferedInputStream (new FileInputStream(fileToDownload)); int ch; while ((ch = in.read()) != -1) { outs.print((char) ch); } } finally { if (in != null) in.close(); // very important } outs.flush(); outs.close(); in.close(); :thumb: [ May 05, 2008: Message edited by: Subhradip Podder ] [ May 05, 2008: Message edited by: Subhradip Podder ] ... More often than not, this will fail. JSPs are a poor choice of technology for streaming data through the servlet output stream.
Top answer
1 of 2
6

You could create a file and -without storing it on the server- return it immediately as a downloadable file to the client.

This has the advantage that you don't need temporary storage on your server that might grow and keep growing unless you regularly clean it out.

Ofcourse if you wish to create an "archive" of old CSV files as a service to your clients then this is no real advantage. But most of the time the 'create/offer-for-download/throw-away' is the more interesting approach.

Here's some example code that may give you some idea:

1) the servlet (note: exception handling not shown)

public class CsvDownloadServlet extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
    // fetch parameters from HTTP request

    String param = (String)request.getParameter("p");
    if (param == null)
    {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Parameter p missing");
        return;
    }

    .... perhaps fetch more parameters ....

    .... build your CSV, using the parameter values ....

    String result = .... // suppose result is your generated CSV contents
    String filename = .... // choose a file name that your browser will suggest when saving the download

    // prepare writing the result to the client as a "downloadable" file

    response.setContentType("text/csv");
    response.setHeader("Content-disposition", "attachment; filename=\""+filename+"\"");
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Expires", "-1");

    // actually send result bytes
    response.getOutputStream().write(result.getBytes());
}
}

2) configuration in WEB-INF/web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      version="3.0"> 
     ....
    <servlet>
        <display-name>download</display-name>
        <servlet-name>download</servlet-name>
        <servlet-class>com.mypackage.CsvDownloadServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>download</servlet-name>
        <url-pattern>/download</url-pattern>
    </servlet-mapping>
    ....
</web-app>

3) the link on your page to trigger the download:

<a href="/myapp/download?p=myparamvalue">Click Here</a>

Here, /myapp is the "context-root" of your application, /download is configured in web.xml to be the location that triggers the CsvDownloadServlet code. p is an example parameter (see servlet code). If you have a form where the user fills in the parameter values, it could look like this:

 <form method='GET' action='/myapp/download'>
    Enter a value for parameter "p":
    <input id="p" type="text" size="10" name="p">
    <input type="submit" value="Generate and Download">
 </form>

This has the same effect as the previous <a> link, only the parameters are user supplied. As soon as the user clicks the submit button, the servlet code will be invoked and the CSV generation and subsequent download will start. Again, user input checking is not shown.

2 of 2
-4

Use this code:

<a href="path for the file" download="filename with extension"><u>Download</u></a>
🌐
C# Corner
c-sharpcorner.com › blogs › how-to-download-file-from-server-using-jsp1
How to Download File from Server using JSP
May 6, 2014 - In the below example we are going to show the demo coding of downloading admin.jsp file from remote server which is located in c:drive(let's say) at server, you can change the location as per your convenience.
🌐
Coderanch
coderanch.com › t › 473496 › java › download-file-server-client-machine
How to download a file from the server to the client machine? (JSP forum at Coderanch)
I need to download a .ldif file from the server onto the client machine. The file gets generated a while after a pop-up is displayed and the user will have to click on the link shown on the pop-up before he could save the file on his machine. Could anyone please provide me a solution to this. Not able to get a right javascript that could do this. My front end is a JSP and backend is only pure java.
🌐
Oracle
forums.oracle.com › ords › apexds › post › jsp-servlet-download-file-from-server-to-client-2107
(JSP Servlet) download file from server to client - Oracle Forums
September 26, 2008 - i have some code for download file from server to client. user can select path file to save by dialog open/save/cancel. after download finish i want to reload jsp page to display data that change. bu...
🌐
Coderanch
coderanch.com › t › 288554 › java › download-file-client-machine
How to download the file to the client machine (JSP forum at Coderanch)
JSP pages run on the server. Whatever code you put in there will not be able to access the client (unless the client hard drive is specifically mapped and made available to the server, but that is not the case in general). Can't you put a link to the file on the HTML page you're generating, so that the user can click on it, and save the file wherever she wants on the local machine?
🌐
Javatpoint
javatpoint.com › downloading-file-from-the-server-in-jsp
Downloading File from the Server in JSP - javatpoint
JSP downloading file from server in jsp with examples of session tracking, implicit objects, el, jstl, mvc, custom tags, file upload, file download, interview questions etc.
🌐
RoseIndia
roseindia.net › answers › viewqa › JSP-Servlet › 3696-File-download-from-server-to-client-machine.html
File download from server to client machine
Delete a file from FTP Server In this section you will learn how to delete file from FTP server using java · URL file Download and Save in the Local Directory URL file Download and Save in the Local Directory This Program file download from URL and save this Url File in the specified directory. This program specifies · Download file - JSP-Servlet Servlet download file from server I am looking for a Servlet download file example
Find elsewhere
🌐
Dot Net Tutorials
dotnettutorials.net › home › file uploading and downloading in jsp
File Uploading and Downloading in JSP - Dot Net Tutorials
March 14, 2021 - In this example, we are downloading a file from a directory by clicking on the link in the “input.html” file. We have given a link to download a file from folder g:/data using the “download.jsp” file. In this, we are setting the content type using the response object and creating FileInputstream in which we will add path and file.
🌐
Oracle Community
community.oracle.com › groundbreakers developer community › java ee (java enterprise edition) › javaserver pages (jsp) and jstl
download file from server in jsp — oracle-tech
September 12, 2011 - 841044 wrote: hi i have uploaded a file to my server,, now i have to create a link for that file and download it to the client machine again.... how to perform this task..??The downloading part the browser does for you, so no worries there. If you want a user to be able to download a file, the browser has to be able to reach it through a HTTP call.
🌐
DigitalOcean
digitalocean.com › community › tutorials › servlet-upload-file-download-example
Servlet Upload File and Download File Example | DigitalOcean
August 3, 2022 - We will use this object in the doPost() method implementation to upload file to server directory. Once the file gets uploaded successfully, we will send response to client with URL to download the file, since HTML links use GET method,we will append the parameter for file name in the URL and we can utilise the same servlet doGet() method to implement file download process.
🌐
Guru99
guru99.com › home › jsp › jsp file upload and download
JSP File Upload and Download
October 9, 2024 - Code Line 31-33: Here we have taken a while loop which will run till the file is read, hence we have given condition as != -1. In this condition we are writing using printwriter object out. When you execute the above code you will get the following output ... We have to click on downloading_1.jsp we will get a hyperlink as “Download Here”. When you click on this hyperlink file, it will downloaded into the system.
🌐
GeeksforGeeks
geeksforgeeks.org › advance java › jsp-file-downloading
JSP - File Downloading - GeeksforGeeks
March 14, 2024 - ... Note: Replace the filename and filepath with your filename and filepath in the code. Step 2: Create a new folder named "filedownload". Create index.html, download-pdf.jsp, download-txt.jsp in the "filedownload" folder and move the folder ...
🌐
CodeJava
codejava.net › java-ee › servlet › java-servlet-download-file-example
Java Servlet File Download Example
package net.codejava; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DownloadFileServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // reads input file from an absolute path String filePath = "E:/Test/Download/MYPIC.JPG
Top answer
1 of 2
2

I am posting here for anybody here who looking for answer on it.

On JSP file, use this for link

<<li><a href="/reportFetch?filePath=<%=file.getAbsolutePath()%>&fileName=<%=file.getName()%>" target="_top"><%=list[i]%></a><br>

and create the servlet

...

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;

import java.io.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/reportFetch")
public class Report extends HttpServlet {

    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String filePath = request.getParameter("filePath");
        String fileName = request.getParameter("fileName");

        MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
        String mimeType = mimeTypesMap.getContentType(request.getParameter("fileName"));

        response.setContentType(mimeType);
        response.setHeader("Content-disposition", "attachment; filename=" + fileName);

        OutputStream out = response.getOutputStream();
        FileInputStream in = new FileInputStream(filePath);
        byte[] buffer = new byte[4096];
        int length;
        while ((length = in.read(buffer)) > 0) {
            out.write(buffer, 0, length);
        }
        in.close();
        out.flush();

    }


    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }
}
2 of 2
0

For some reason, the above answers failed, but this solution works:

index.jsp

<form action="download" method="GET">
    <input type="hidden" name="filePath" value="<%=file.getAbsolutePath()%>" />
    <input type="hidden" name="fileName" value="<%=file.getName()%>" />
    <input type="submit" value="DOWNLOAD" />
</form>

DownloadServlet.java

import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.activation.MimetypesFileTypeMap;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
  
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    String filePath = req.getParameter("filePath");
    String fileName = req.getParameter("fileName");
    
    MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
    String mimeType = "APPLICATION/OCTET-STREAM";
    if (null != fileName && !"".equals(fileName)) {
      mimeType = mimeTypesMap.getContentType(fileName);
    } else {
      fileName = "file.unknown";
    }
    
    if (filePath != null) {
      resp.setContentType(mimeType);
      resp.setHeader("Content-disposition", "attachment; filename=" + fileName);
      OutputStream out = resp.getOutputStream();
      FileInputStream in = new FileInputStream(filePath);
      byte[] buffer = new byte[4096];
      int length;
      while ((length = in.read(buffer)) > 0) {
        out.write(buffer, 0, length);
      }
      in.close();
      out.flush();
    } else {
      resp.getOutputStream().println("400 Bad Request, please provide the required parameters: /download?filePath=...&fileName=...");
    }
  }
  
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    this.doGet(req, resp);
  }
  
}
🌐
RoseIndia
roseindia.net › answers › viewqa › JSP-Servlet › 626-Download-file.html
Servlet download file from server
Download CSV File from Database in JSP Download CSV File from Database in JSP ... to download CSV file from database in JSP. In this example, we have... and download the CSV file from database. All CSV file will show · Create text file at client's directory from server.
🌐
Coderanch
coderanch.com › t › 292104 › java › download-file-jsp
How can I download a file from a jsp? (JSP forum at Coderanch)
The part that I am confused by right now is, how can I let them navigate the windows folder system so they can specify what folder to save the file to and what to name the file? Thank you for any pointers, Kim ... The Content-Disposition header allows you to mark a response as either "inline" or "attachment". The "attachment" value suggests that the browser open the "What do you want to do with this?" dialog. If the machine has the proper application installed (Adobe Acrobat for instance), the user can choose to either open it or save it. There is an example of this tag in the JSP FAQ.
🌐
Coderanch
coderanch.com › t › 537117 › java › Download-File-server-client-machine
Download a File from server to client machine - web application (Servlets forum at Coderanch)
Ajeeth Kumar wrote:I am sure that you can download the files from server using the response object and by setting the response type as "application/pdf" in the resultant jsp header. I am also implementing the same behaviour in a web app and it works fine in windows Except that that will not meet the (impossible) requirements of the original poster to write the file automatically to the file system of the client machine without user intervention.