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

22,461

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

}
Share:
22,461
Venkat Maridu
Author by

Venkat Maridu

Updated on July 18, 2022

Comments

  • Venkat Maridu
    Venkat Maridu almost 2 years

    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?

  • Kishor Prakash
    Kishor Prakash over 10 years
    What if I keep my ManagedBean in @ViewScoped ?
  • BalusC
    BalusC over 4 years
    It will fail: stackoverflow.com/q/18994288 Always use a stateless bean with <f:param> for serving StreamedContent.