Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 694
Venkat Maridu Avatar asked Jan 09 '13 09:01

Venkat Maridu


1 Answers

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

}
like image 101
BalusC Avatar answered Nov 14 '22 22:11

BalusC