jsfjsf-2primefacesdownloadajax-polling

It is possible to download file on p:poll


I'm trying to download file by p:poll.

Here is my code:

<p:commandButton id="sendMessage" value="sendMessage" actionListener="#{logsController.sendMessage}" />
<p:poll interval="3" async="false"  immediate="true" listener="#{logsController.downloadAll(null)}" />

and backing bean:

public void sendMessage( ActionEvent event ) {
   {adding message to queue}
}

public void downloadAll( ActionEvent event ) {
   ...
   if(readyToDownload) {
      Faces.sendFile(logFile.getFileByteArray(), "file.txt", true);
   }
}

I wish open up the "save as" dialog but I get only JQuery json parse error.

A content which I'm trying download is a message result from external api, so I can't get this suddenly.

Maybe is another way to solve this problem?


Solution

  • Nope. You can't respond with a whole file attachment as ajax response. First of all, jQuery would get confused because it got a file attachment instead of the expected XML/JSON response with instructions what to do with HTML DOM tree. Secondly, JavaScript has for obvious security reasons no facilities to force a Save As dialogue providing file content held in an arbitrary JavaScript variable.

    The file download has really to take place during a synchronous request. Exactly such request as fired with <h:commandButton>, <p:commandButton ajax="false">, or window.location.

    Your best bet is to return a JavaScript instruction to invoke a synchronous request. E.g.

    if (readyToDownload) {
        RequestContext.getCurrentInstance().execute("document.getElementById('form:download').click();");
    }
    
    <h:form id="form">
        <p:commandButton id="download" styleClass="ui-helper-hidden"
            action="#{logsController.downloadFile}" ajax="false" />
    </h:form>
    

    And then actually send the file in downloadFile() method.