在操作方法(JSF)中,我有如下内容:
public String getFile() {
byte[] pdfData = ...
// how to return byte[] as file to web browser user ?
}
如何将 byte[] 作为 pdf 发送到浏览器?
在操作方法中,您可以通过以下方式从 JSF 底层获取 HTTP servlet 响应:ExternalContext#getResponse() http://java.sun.com/javaee/5/docs/api/javax/faces/context/ExternalContext.html#getResponse%28%29。那么你至少需要设置HTTPContent-Type
标头至application/pdf
和 HTTPContent-Disposition
标头至attachment
(当你想弹出一个Save As对话)或inline
(当您想让网络浏览器自行处理显示时)。最后,您需要确保您调用FacesContext#responseComplete() http://java.sun.com/javaee/5/docs/api/javax/faces/context/FacesContext.html#responseComplete()之后避免IllegalStateException
飞来飞去。
开球示例:
public void download() throws IOException {
// Prepare.
byte[] pdfData = getItSomehow();
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
HttpServletResponse response = (HttpServletResponse) externalContext.getResponse();
// Initialize response.
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/pdf"); // 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.pdf\""); // 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.
// Write file to response.
OutputStream output = response.getOutputStream();
output.write(pdfData);
output.close();
// Inform JSF to not take the response in hands.
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.
}
也就是说,如果您有机会获得 PDF 内容InputStream
而不是一个byte[]
,我建议使用它来避免 web 应用程序占用大量内存。然后你只需将其写在众所周知的InputStream
-OutputStream
循环通常的 Java IO 方式。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)