How to download a file stored in a database with JSF 2.0

前端 未结 1 1241
傲寒
傲寒 2021-01-05 17:15

I need to download a file stored in a database. I think i did correctly the query and called it i just dont know how can i connect that to a button in a JSF page. Also i am

相关标签:
1条回答
  • 2021-01-05 17:37

    Passing parameters in EL only works when the web.xml is declared as Servlet 3.0 and the servletcontainer also supports it (Glassfish 3, JBoss AS 6, Tomcat 7, etc). There's only a syntax error in your attempt, here's the correct way:

    <h:commandButton action="#{downloadController.startDownload(garbage.id)}" />
    

    You can even pass whole objects along, that's better in this particular case.

    <h:commandButton action="#{downloadController.startDownload(garbage)}" />
    

    Then, the startDownload() method should set the response headers so that the webbrowser understands what content type the response body represents and what to do with it and finally write the content to the response body. You can do it all with help of ExternalContext. Here's a kickoff example:

    public void startDownload(Garbage garbage) {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        ExternalContext externalContext = facesContext.getExternalContext();
        externalContext.setResponseHeader("Content-Type", garbage.getContentType());
        externalContext.setResponseHeader("Content-Length", garbage.getContent().length);
        externalContext.setResponseHeader("Content-Disposition", "attachment;filename=\"" + garbage.getFileName() + "\"");
        externalContext.getResponseOutputStream().write(garbage.getContent());
        facesContext.responseComplete();
    }
    

    The last line with FacesContext#responseComplete() is mandatory so that JSF understands that it shouldn't navigate to some view and thus potentially malform the response with another JSF page afterwards.

    0 讨论(0)
提交回复
热议问题