从JSF应用程序的任何Web浏览器强制保存为对话框

时间:2010-05-26 14:48:01

标签: java jsf

我已经创建了一个JSF应用程序,并且我想在页面中嵌入一个链接,当单击该链接时会导致支持bean编组一些xm​​l并强制打开另存为下载对话框,以便用户可以选择保存文件的位置。我已经编写了JAXB代码。

这是怎么做到的?

由于

3 个答案:

答案 0 :(得分:33)

将HTTP Content-Disposition标头设置为attachment。这将弹出另存为对话框。您可以使用HttpServletResponse#setHeader()执行此操作。您可以通过ExternalContext#getResponse()从JSF引擎下获取HTTP servlet响应。

在JSF环境中,您只需要确保之后调用FacesContext#responseComplete()以避免IllegalStateException飞来飞去。

开球示例:

public void download() throws IOException {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType("application/xml"); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setHeader("Content-disposition", "attachment; filename=\"name.xml\""); // The Save As popup magic is done here. You can give it any filename you want, this only won't work in MSIE, it will use current request URL as filename instead.

    BufferedInputStream input = null;
    BufferedOutputStream output = null;

    try {
        input = new BufferedInputStream(getYourXmlAsInputStream());
        output = new BufferedOutputStream(response.getOutputStream());

        byte[] buffer = new byte[10240];
        for (int length; (length = input.read(buffer)) > 0;) {
            output.write(buffer, 0, length);
        }
    } finally {
        close(output);
        close(input);
    }

    facesContext.responseComplete(); // Important! Else JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

答案 1 :(得分:3)

使用content-disposition: attachment HTTP标头

答案 2 :(得分:0)

有时您需要强制编写器在关闭编写器之前通过调用response.getWriter().flush();将内容发送到客户端。这导致我的情况下保存为弹出窗口。