如何在java Web应用程序中将byte[]作为pdf发送到浏览器?
在行动方法(JSF)我有如下内容:
public String getFile() {
byte[] pdfData = ...
// how to return byte[] as file to web browser user ?
}
如何将byte[]作为pdf发送到浏览器?
在行动方法(JSF)我有如下内容:
public String getFile() {
byte[] pdfData = ...
// how to return byte[] as file to web browser user ?
}
如何将byte[]作为pdf发送到浏览器?
在操作方法中,您可以通过 ExternalContext#getResponse()
从 JSF 引擎盖下获取 HTTP servlet 响应。然后,您至少需要将HTTP标头设置为HTTP标头,并将HTTP标头设置为(当您要弹出“另存为”对话框时)或设置为(当您想让Web浏览器处理显示本身时)。最后,你需要确保你之后调用FacesContext#responseComplete()
以避免飞来飞去。Content-Type
application/pdf
Content-Disposition
attachment
inline
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内容作为而不是获取,我建议使用它来保存Web应用程序免于内存占用。然后,您只需以众所周知的方式编写它 - 循环通常的Java IO方式。InputStream
byte[]
InputStream
OutputStream
您只需要将哑剧类型设置为您的响应即可。您可以使用 setContentType(String contentType) 方法在 servlet 情况下执行此操作。
在 JSF/JSP 中,在编写响应之前,您可以使用以下命令:application/x-pdf
<%@ page contentType="application/x-pdf" %>
并写入您的数据。
但是我真的建议你在这种情况下使用servlet。JSF 用于呈现 HTML 视图,而不是 PDF 或二进制文件。response.write(yourPDFDataAsBytes());
对于 servlet,您可以使用以下命令:
public MyPdfServlet extends HttpServlet {
protected doGet(HttpServletRequest req, HttpServletResponse resp){
OutputStream os = resp.getOutputStream();
resp.setContentType("Application/x-pdf");
os.write(yourMethodToGetPdfAsByteArray());
}
}
资源: