JSP - Allow user to download files from server

13,441

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.

Share:
13,441
Playmaker
Author by

Playmaker

A techno manger by profession, I have completed my MBA (tech) with specialization in Information Technology &amp; Finance. SOreadytohelp

Updated on July 16, 2022

Comments

  • Playmaker
    Playmaker almost 2 years

    I have written a program in Java/JSP which dynamically creates a CSV file based on user input and stores it (on the server).

    How can I allow the user to download this file?

    Currently using the following to decide the path to store the file.

    String csv2 = "D:\\erp\\Dispatch\\DC_" + (df.format(date)).toString() + "_Print.csv";
    CSVWriter writer2 = new CSVWriter(new FileWriter(csv2));
    

    According to my research, the best bet is to store it in the web-directory and provide the relative path to the file. In that case, where should I store the file (or how should I store it to the web-directory)?

    NOTE: The above path is being set in the JSP, and hence I can use the same variables to provide the URL/path to the users

    NOTE 2: Server is a tomcat server

  • Playmaker
    Playmaker over 9 years
    Thanks bro. I've already solved this issue (fgot to close). Yours seems to be a more comprehensive way though :)