从JSF应用程序的任何Web浏览器强制保存为对话框 [英] Forcing a save as dialogue from any web browser from JSF application

查看:165
本文介绍了从JSF应用程序的任何Web浏览器强制保存为对话框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've created a JSF application, and I want to embed a link in a page which when clicked causes the backing bean to marshall out some xml and force the opening of a save-as download dialogue box so the user can choose a location to save the file. I've already written the JAXB code.

这是怎么做的?

谢谢

推荐答案

将HTTP Content-Disposition 标头设置为附件。这将弹出另存为对话框。你可以使用 HttpServletResponse #setHeader() 。您可以通过 ExternalContext#getResponse()

Set the HTTP Content-Disposition header to attachment. This will pop a Save As dialogue. You can do that using HttpServletResponse#setHeader(). You can obtain the HTTP servlet response from under the JSF hoods by ExternalContext#getResponse().

在JSF上下文中,仅限于需要确保你打电话给 FacesContext #responseComplete() 之后避免 IllegalStateException s飞来飞去。

In JSF context, you only need to ensure that you call FacesContext#responseComplete() afterwards to avoid IllegalStateExceptions flying around.

Kickoff示例:

Kickoff example:

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

这篇关于从JSF应用程序的任何Web浏览器强制保存为对话框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆