java JSP - 允许用户从服务器下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27475077/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 11:52:03  来源:igfitidea点击:

JSP - Allow user to download files from server

javahtmljsp

提问by Playmaker

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

我用 Java/JSP 编写了一个程序,它根据用户输入动态创建一个 CSV 文件并将其存储(在服务器上)。

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)?

根据我的研究,最好的办法是将它存储在 web 目录中并提供文件的相对路径。在这种情况下,我应该在哪里存储文件(或者我应该如何将它存储到网络目录)?

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

注意:上面的路径是在 JSP 中设置的,因此我可以使用相同的变量向用户提供 URL/路径

NOTE 2: Server is a tomcat server

注2:服务器为tomcat服务器

回答by geert3

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.

当然,如果您希望创建旧 CSV 文件的“存档”作为对客户的服务,那么这不是真正的优势。但大多数情况下,“创建/提供下载/丢弃”是更有趣的方法。

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

下面是一些示例代码,可能会给您一些想法:

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

1) servlet(注意:未显示异常处理)

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

2)在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:

3)您页面上的链接触发下载:

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

Here, /myappis the "context-root" of your application, /downloadis configured in web.xmlto be the location that triggers the CsvDownloadServletcode. pis an example parameter (see servlet code). If you have a form where the user fills in the parameter values, it could look like this:

在这里,/myapp是应用程序的“上下文根”,/download被配置web.xml为触发CsvDownloadServlet代码的位置。p是一个示例参数(参见 servlet 代码)。如果您有一个用户填写参数值的表单,它可能如下所示:

 <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.

这与上一个<a>链接的效果相同,只是参数是用户提供的。只要用户单击提交按钮,就会调用 servlet 代码,并开始 CSV 生成和后续下载。同样,未显示用户输入检查。

回答by Leo

Use this code:

使用此代码:

<a href="path for the file" download="filename with extension"><u>Download</u></a>