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

从JSF应用程序的任何Web浏览器中强制进行另存为对话框,第1张

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

将HTTP

Content-Disposition
标头设置为
attachment
。这将d出一个 另存为
对话框。您可以使用进行 *** 作
HttpServletResponse#setHeader()
。您可以通过JSF幕后获得HTTP
servlet响应
ExternalContext#getResponse()


在JSF上下文中,只需要确保

FacesContext#responseComplete()
稍后再调用即可避免
IllegalStateException
s飞散

开球示例:

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


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5176277.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-18
下一篇 2022-11-18

发表评论

登录后才能评论

评论列表(0条)

保存