gpt4 book ai didi

java - java - 如何在Java Web应用程序中将字节[]作为pdf发送到浏览器?

转载 作者:IT老高 更新时间:2023-10-28 21:03:52 27 4
gpt4 key购买 nike

在行动方法(JSF)中,我有如下内容:

public String getFile() {
byte[] pdfData = ...
// how to return byte[] as file to web browser user ?
}

如何将 byte[] 作为 pdf 格式发送到浏览器?

最佳答案

在 action 方法中,您可以通过 ExternalContext#getResponse() 从 JSF 引擎盖下获取 HTTP servlet 响应。 .然后您需要至少将 HTTP Content-Type header 设置为 application/pdf 并将 HTTP Content-Disposition header 设置为 attachment (当你想弹出 Save As 对话框时)或 inline(当你想让 webbrowser 自己处理显示时)。最后,您需要确保调用 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.
}

也就是说,如果您有可能将 PDF 内容作为 InputStream 而不是 byte[],我建议使用它来保存来自内存 pig 的 webapp。然后,您只需将其写入众所周知的 InputStream-OutputStream 循环通常的 Java IO 方式。

关于java - java - 如何在Java Web应用程序中将字节[]作为pdf发送到浏览器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3592058/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com