在操作方法(JSF)中,我有如下内容:
public String getFile() {
byte[] pdfData = ...
// how to return byte[] as file to web browser user ?
}
如何将byte[]以pdf格式发送到浏览器?
发布于 2010-08-29 04:11:44
在操作方法中,您可以通过ExternalContext#getResponse()
从JSF内部获取HTTP servlet响应。然后,您至少需要将header设置为application/pdf
,并将header设置为attachment
(当您想要弹出一个“另存为”对话框时)或设置为inline
(当您想让let浏览器自己处理显示时)。最后,您需要确保在事后调用FacesContext#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.
}
也就是说,如果您有可能以InputStream
而不是byte[]
的形式获取PDF内容,我建议您使用它来节省get应用程序的内存消耗。然后,您只需以通常的InputStream
IO方式在众所周知的Java -OutputStream
循环中编写它。
https://stackoverflow.com/questions/3592058
复制相似问题