首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在java web应用程序中将byte[]以pdf格式发送到浏览器?

如何在java web应用程序中将byte[]以pdf格式发送到浏览器?
EN

Stack Overflow用户
提问于 2010-08-29 03:06:04
回答 1查看 63K关注 0票数 19

在操作方法(JSF)中,我有如下内容:

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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循环中编写它。

票数 54
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3592058

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档