content disposition with attachment doesnt work for AJAX response

一世执手 提交于 2020-01-03 04:16:07

问题


The problem for me is pretty straight forward. Onclick of an anchor tag , I execute a javascript using a4j:jsFunction and the action of this function should stream an XML file from server. The problem is , the stream sent on richfaces response doesnt give a saveAs dialog but instead renders the xml on the browser. After reading many articles I understood that Ajax response cannot give a saveAs Dialog.

xhtml snippet:

<h:form>
        <a4j:jsFunction name="updateCart" reRender="idFavouritePanel">
            <a4j:actionparam name="jsonObject" assignTo="#{archiveOrderBean.jsonObject}"/>
        </a4j:jsFunction>

         <a4j:jsFunction  name="download" reRender="partTableId" action="#{archiveOrderBean.loadSelectedOrder}">
            <a4j:actionparam name="strId" assignTo="#{archiveOrderBean.strId}"  />
        </a4j:jsFunction>
</h:form>

and the response set from bean.

response.setContentType("application/xml");
                    response.setContentLength(byteArr.length);
                    response.addHeader("Content-Disposition", "attachment; filename=" + attr.getUrl());
//                  writer.write(byteArr.toString());
//                  writer.flush();
                    response.getOutputStream().write(byteArr);
                    response.getOutputStream().flush();
                    // post(trueStr,encPath,encUrl,trueStr,response);
                    FacesContext.getCurrentInstance().responseComplete();

any help in this regard will be really helpful.


回答1:


Yes, you can't trigger saveAs dialog with ajax. What you can do is return a URL. Then open that URL (with javascript). The server should then send the file (with the appropriate headers). Of course, you can skip all that and just give a link to the URL in question (unless it is dynamically generated)




回答2:


I could solve this problem with the crude method not very recommended but with no alternative.

I added a hidden h:commandButton and moved the attribute action="#{archiveOrderBean.loadSelectedOrder}" from the a4j:jsFunction, On completion of javascript execution I explicitly call the click event for h:commandButton using javascript. This will synchronous request for the XML. In short decieving the click event.

This was one way I had to do the changes since the XML was created at runtime. The other way is as explained by @Bozho.

Thank you @BalusC for your help :-)



来源:https://stackoverflow.com/questions/7684297/content-disposition-with-attachment-doesnt-work-for-ajax-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!