链接在JSF下载zip文件

Gra*_*te 2 jsf download primefaces

我在服务器上有一个zip文件.我想点击链接下载该文件.

有没有办法创建一个链接来下载JSF或PrimeFaces中的zip文件,如下面download的客户端HTML5 属性?

<a href="/images/myw3schoolsimage.jpg" download>
Run Code Online (Sandbox Code Playgroud)

Bal*_*usC 8

HTML5 download属性与它无关.它只允许您指定应在" 另存为"对话框中显示的备用文件名.

例如

<a href="foo.zip" download="bar.zip" />
Run Code Online (Sandbox Code Playgroud)

将以文件名显示" 另存为"对话框bar.zip,但实际上提供了内容foo.zip.请注意,bar.zip服务器中不一定需要存在.


至于您的具体问题,有几种方法可以在JSF Web应用程序中提供文件下载.

  1. 只需将该文件放在公共Web内容文件夹中即可.

    WebContent
     |-- META-INF
     |-- WEB-INF
     |-- files
     |    `-- foo.zip
     |-- page.xhtml
     :
    
    Run Code Online (Sandbox Code Playgroud)

    然后你可以把它称为:

    <a href="#{request.contextPath}/files/foo.zip">download foo.zip</a>
    
    Run Code Online (Sandbox Code Playgroud)
  2. 或者,如果它是外部文件夹而您无法将其移动到公共Web内容中,那么只需告诉服务器发布它.例如,当您在/path/to/files路径中拥有所有这些文件并且您正在使用Tomcat服务器时,请将以下内容添加到<Host>Tomcat的元素中/conf/server.xml:

    <Context docBase="/path/to/files" path="/files" />
    
    Run Code Online (Sandbox Code Playgroud)

    然后你可以把它称为:

    <a href="/files/foo.zip">download foo.zip</a>
    
    Run Code Online (Sandbox Code Playgroud)
  3. 或者,如果您无法以某种方式控制服务器配置,或者无法确定将服务器特定的文件夹作为新的Web上下文发布的特定于服务器的方式,或者它代表您不想发布到Web的临时存储文件夹,然后创建一个完成工作的Web servlet.将缓存和恢复留在外面考虑,就像这样简单:

    @WebServlet("/files/*")
    public class FileServlet extends HttpServlet {
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String filename = request.getPathInfo().substring(1);
            File file = new File("/path/to/files", filename);
            response.setHeader("Content-Type", getServletContext().getMimetype(filename));
            response.setHeader("Content-Length", String.valueOf(file.length()));
            response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
            Files.copy(file.toPath(), response.getOutputStream());
        }
    
    }
    
    Run Code Online (Sandbox Code Playgroud)

    您可以像#1一样引用它:

    <a href="#{request.contextPath}/files/foo.zip">download foo.zip</a>
    
    Run Code Online (Sandbox Code Playgroud)