5 Replies Latest reply on Jan 29, 2009 5:35 AM by nbelaevski

    Binary response on ajax request

    koloale1

      Hello!

      I want to provide a binary response (i.e. send file) in an action listener on an ajax request, but a browser opens this binary file as a text in the existent window instead of the previous page. Ajax request is generated by <a4j:commandButton>. If I change a4j:commandButton to h:command all works fine, the browser opens up a saveas window.
      Is it possible to open up that saveas window in the case of the AJAX request either?

      P.S. In the action listener I get raw HttpServletResponse, set content to "application/octet-stream", write content to output stream and call FacesContext.getCurrentInstance().responseComplete(); at the enf of the listener.

      Many thanks in advance,
      Alexey

        • 1. Re: Binary response on ajax request
          nbelaevski

          Hello Alexey,

          No, it's not possible to do this by AJAX.

          • 2. Re: Binary response on ajax request
            nbelaevski

            BTW, you can do redirect to the file, if you need. It'll be requested in a separate request then.

            • 3. Re: Binary response on ajax request

              Ajax is used for partial page update. Trying to download anything also, it a bad idea by definition.

              When you click on the regular link to download html or binary file, the request is sent by the browser itself. Then, when response comes, the browser decides what to do with it (to show in the window as a new document or open by an external program or offer the saveas window)

              When the Ajax request performs, it is sent by the XMLHTTPRequest object. The object expects that response is in the XML format. XMLHTTPRequest object cannot launch the external program based on the content type or saveas dialog, because XMLHTTPRequest != browser. It has no permissions for such operations.

              • 4. Re: Binary response on ajax request
                koloale1

                Thank you guys for the detailed answers it clears up the internals of ajax very much. The reason why that behavior might be useful is when I want conditionally handle ajax request and in some cases return a file, otherwise report an error and continue work in the existing page, only performing some rerendering.
                I hope redirect would help. Does redirect work for ajax request?

                • 5. Re: Binary response on ajax request
                  nbelaevski

                  Yes, redirect should work ok.