在 Primefaces 中使用 p:media 显示 Pdf

Show Pdf using p:media in Primfaces

我想查看在我的 Oracle 数据库中存储为 blob 的 pdf 文件。我在 xhml 中使用 <p:media/> ,在支持 bean 中使用 StreamedContent

这里是xhtml

<ui:composition xmlns="http://www.w3.org/1999/xhtml"
  xmlns:ui="http://java.sun.com/jsf/facelets"
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:f="http://java.sun.com/jsf/core"
  xmlns:c="http://java.sun.com/jsp/jstl/core"
  xmlns:p="http://primefaces.org/ui">

 <p:outputPanel id="outputPanelDialogShowPdf">

    <div style="text-align: center">
        <p:media value="#{bean.media}" width="600px" height="300px" player="pdf" />
    </div>

    <p:spacer height="1px" />
    <div style="text-align: center">
        <p:commandButton value="#{msgs.button_cancel}" icon="ui-icon-cancel" oncomplete="dialogShowPdf.hide();" 
                         action="#{bean[cancelAction]}" immediate="true" />
    </div>
</p:outputPanel>

这里是调用动作 bean

的动作按钮(它是数据 table 的一部分)
    <p:commandButton value="Show PDF"
                              update=":formMediaDataDialogShowPdf:outputPanelDialogShowPdf" 
                              oncomplete="PF('dialogShowPdf').show()" 
                              action="#{ bean.showPdfAction }" rendered="#{ mediaData.mediaType == 'application/pdf'}"> 
                 <f:setPropertyActionListener value="#{mediaData}" target="#{bean.selectedMediaData}" />
            </p:commandButton> 

这是 bean 中的操作

public void showPdfAction(){

    if (null != selectedMediaData) { 
        media = new DefaultStreamedContent(new ByteArrayInputStream(selectedMediaData.getMediaData()),"application/pdf");   
    }
}

问题是媒体没有显示,即使 bean 中的操作运行没有错误,并且 bean 中的 media 属性 被正确初始化。

任何人都可以为此提供一些帮助

经过几个小时的研究,我找到了一个非常适合我的解决方案。

我已经更新了bean中的动作如下

if (null != selectedMediaData) { 
    FacesContext facesContext = FacesContext.getCurrentInstance();
    HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);

    session.setAttribute("pdfBytesArray", selectedMediaData.getMediaData());
}

现在,当我将 pdfBytesArray 作为会话属性传递时,我创建了一个 servlet,我可以在其中从会话中获取此属性,然后处理字节数组,然后使用application/pdf

的内容类型
public class PdfPreviewServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    byte[] pdfBytesArray = (byte[]) request.getSession().getAttribute("pdfBytesArray");
    request.getSession().removeAttribute("pdfBytesArray");
    response.setContentType("application/pdf");
    response.setContentLength(pdfBytesArray.length);
    response.getOutputStream().write(pdfBytesArray);
} }

然后用@WebServlet("/pdfPreviewServlet")

注释servlet

然后将<p:media/>改为<p:media value="/pdfPreviewServlet" player="pdf"/>