用JSF下载文件?

ErV*_*VeY 15 java jsf download

哪个是使用JSF下载文件的正确方法?只是放一个文件链接?在那种情况下我如何获得文件URL?

我见过一个使用BufferedInputStream的例子:

http://www.winstonprakash.com/articles/jsf/file_download_link.htm

有什么区别?

谢谢

Bal*_*usC 24

如果它是一个简单的文件,只需放在公共webcontent(放置静态和JSF文件的地方)并创建一个链接.

<h:outputLink value="/files/file.ext">link</h:outputLink>
Run Code Online (Sandbox Code Playgroud)

servletcontainer将担心应用正确的标头.

如果出于某些特定原因(例如,在服务器计算机的固定路径或数据库中),它位于公共webcontent之外,那么创建一个获取InputStream它的servlet并将其写入OutputStream至少响应的响应Content-Type,Content-Disposition并且Content-Length头.你可以在这里找到一个简单的启动示例.这也可以简单地链接在servlet上url-pattern.

如果它是动态生成的并且取决于JSF特定的请求参数,那么您也可以在受到h:commandLink或者绑定的托管bean操作中执行此操作h:commandButton,但是您只需要确保FacesContext#responseComplete()在bean的操作方法结束时调用以防止JSF从手中导航.可以重用相同类型的servlet代码来传输文件.您可以在此答案中找到启动示例.


Mar*_*ier 13

我需要制作类似的代码来通过JSF下载文件

这是我在JSF页面中的下载按钮

<h:commandButton value="Download" action="#{helloBean.downloadFile}" />
Run Code Online (Sandbox Code Playgroud)

这是我的Java代码

public void downloadFile() {

    File file = new File("/home/marco/file.txt");
    HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();  

    response.setHeader("Content-Disposition", "attachment;filename=file.txt");  
    response.setContentLength((int) file.length());  
    ServletOutputStream out = null;  
    try {  
        FileInputStream input = new FileInputStream(file);  
        byte[] buffer = new byte[1024];  
        out = response.getOutputStream();  
        int i = 0;  
        while ((i = input.read(buffer)) != -1) {  
            out.write(buffer);  
            out.flush();  
        }  
        FacesContext.getCurrentInstance().getResponseComplete();  
    } catch (IOException err) {  
        err.printStackTrace();  
    } finally {  
        try {  
            if (out != null) {  
                out.close();  
            }  
        } catch (IOException err) {  
            err.printStackTrace();  
        }  
    }  

}
Run Code Online (Sandbox Code Playgroud)

  • 我认为这个答案有错误。你必须在最后调用 `FacesContext.getCurrentInstance().responseComplete()`(而不是 `getResponseComplete`) (3认同)
  • 命令按钮的action方法不应该返回一个String吗? (2认同)