Question

How can I use an image from a database as a CSS background-image? I can get an image from the resource library (file), but not the DB.

<h:outputStylesheet>
   body {
      background-image:url("#{resource[imageBean.getImage().getUrl()]}"); 
   }
</h:outputStylesheet>

resource[imageBean.getImage().getUrl()

Is there a way I can get the URL of the image that is in the imageBean?

I display DB images using an application scoped bean: Displaying images from MySQL database in JSF datatable

Était-ce utile?

La solution

Use a normal servlet.

@WebServlet("/image")
public class ImageServlet extends HttpServlet {

    @EJB
    private ImageService service;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Image image = service.find(request.getParameter("id"));
        response.setContentType(image.getContentType());
        response.setContentLength(image.getContent().length);
        response.setHeader("Content-Disposition", "inline;filename=\"" + URLEncoder.encode(image.getFilename(), "UTF-8") + "\"");
        response.getOutputStream().write(image.getContent());
    }

}
body {
   background-image:url("#{request.contextPath}/image?id=#{bean.imageId}"); 
}

See also:

Autres conseils

With no response for 9 months I assume there is no clean way of doing this.

Workaround using jQuery:

Get the image from the DB via a bean and hide it with css:

<p:graphicImage styleClass="backgroundImage" style="display:none;" value="#{imageBean.image}">
    <f:param name="imageID" value="12" />
</p:graphicImage>

Then get the path to the image and set the background-image property:

<script>
    if ($('.backgroundImage')) {
        var bgImageSrc = $('.backgroundImage').prop('src');
        $('body').css("background-image", "url(" + bgImageSrc + ")");
    }
</script>

Any improvements or suggestions are welcome.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top