How to bind dynamic content using <p:media>?
Asked Answered
C

1

10

I use the <p:media> to display static PDF content.

<p:media value="/resource/test.pdf" 
         width="100%" height="300px" player="pdf">  
</p:media>

How can I change it to display dynamic content?

Craps answered 9/1, 2013 at 9:47 Comment(0)
A
13

Like as in <p:graphicImage>, the value attribute can point to a bean property returning StreamedContent. This only requires a special getter method for the reasons which is explained in detail in the following answer on using <p:graphicImage> with a dynamic resource from a database: Display dynamic image from database with p:graphicImage and StreamedContent.

In your particular example, it would look like this:

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

With

@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()));
        }
    }

}
Anteroom answered 9/1, 2013 at 11:4 Comment(2)
What if I keep my ManagedBean in @ViewScoped ?Rameriz
It will fail: https://mcmap.net/q/1164707/-primefaces-p-media-not-working-with-streamedcontent-in-a-viewscoped-bean Always use a stateless bean with <f:param> for serving StreamedContent.Anteroom

© 2022 - 2024 — McMap. All rights reserved.