如何使用<p:media>绑定动态内容?

10
我使用 <p:media> 来显示静态的 PDF 内容。
<p:media value="/resource/test.pdf" 
         width="100%" height="300px" player="pdf">  
</p:media>

我怎样才能将其改为显示动态内容?

1个回答

13

就像在<p:graphicImage>标签中一样,value属性可以指向一个返回StreamedContent的bean属性。这只需要一个特殊的getter方法,详细解释了使用从数据库中获取动态资源的<p:graphicImage>的原因,请参阅以下回答:Display dynamic image from database with p:graphicImage and StreamedContent.

在您的特定示例中,代码如下:

<p:media value="#{mediaManager.stream}" width="100%" height="300px" player="pdf">
    <f:param name="id" value="#{bean.mediaId}" />
</p:media>

随着

@ManagedBean
@ApplicationScoped
public class MediaManager {

    @EJB
    private MediaService service;

    public StreamedContent getStream() throws IOException {
        FacesContext context = FacesContext.getCurrentInstance();

        if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) {
            // So, we're rendering the HTML. Return a stub StreamedContent so that it will generate right URL.
            return new DefaultStreamedContent();
        } else {
            // So, browser is requesting the media. Return a real StreamedContent with the media bytes.
            String id = context.getExternalContext().getRequestParameterMap().get("id");
            Media media = service.find(Long.valueOf(id));
            return new DefaultStreamedContent(new ByteArrayInputStream(media.getBytes()));
        }
    }

}

4
如果我将我的ManagedBean保留在@ViewScoped中会怎样? - Kishor Prakash
它会失败:https://dev59.com/_nfZa4cB1Zd3GeqPPDop 始终使用一个无状态的bean和<f:param>来提供StreamedContent - BalusC

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接