要在不使用fileDownloadActionListener的情况下下载文件,我在页面上添加一个按钮:
<af:commandButton text="Download" id="cb1" partialSubmit="true" actionListener="#{bean.downloadListener}"/>
在动作监听器中我写了以下内容:
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.redirect("http://download-server/file");
fc.responseComplete();
问题是,首次下载后按钮停止响应点击次数。
我还尝试将数据写入响应流,如下所示:
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
ec.responseReset();
ec.setResponseContentType("application/xls");
ec.setResponseHeader("Content-Disposition", "attachment; filename=\"report.xls\"");
OutputStream out = ec.getResponseOutputStream();
// write the data
out.close();
fc.responseComplete();
甚至获得HttpServletResponse:
HttpServletResponse resp = (HttpServletResponse)ec.getResponse();
resp.addHeader("Content-Disposition", "attachment; filename=\"report.xls\"");
resp.addHeader("Content-Type", "application/xls");
OutputStream out = resp.getOutputStream();
// write the data
out.close();
fc.responseComplete();
但不起作用。
我该怎么做才能让它发挥作用?
答案 0 :(得分:0)
我使用了一些JavaScript实现了这个:
final FacesContext fc = FacesContext.getCurrentInstance();
final ExtendedRenderKitService erks =
Service.getService(fc.getRenderKit(), ExtendedRenderKitService.class);
erks.addScript(fc, String.format("window.location = '%s';", escapeSingleQuotes(url)));
或者,不是分配window.location
,而是使用内联框架下载:
erks.addScript(
fc,
String.format("var downloadUrl = '%s';", escapeSingleQuotes(url)) +
"var frame = document.createElement('iframe');" +
"frame.setAttribute('src', downloadUrl);" +
"frame.style.border = '0';" +
"frame.style.clip = 'rect(0 0 0 0)';" +
"frame.style.width = '1px';" +
"frame.style.height = '1px';" +
"frame.style.margin = '-1px';" +
"frame.style.padding = '0';" +
"frame.style.position = 'absolute';" +
"document.body.appendChild(frame);"
);