当我单击 h:commandButton
时,它会执行 myBean.dowanlod()
方法,但不会下载任何文件。
这是我在支持 bean 中的方法。没有异常(exception)。光标变忙,似乎在等待响应。这种操作是否有额外的配置,或者这段代码有什么问题吗?
<h:commandButton value="download" action="#{myBean.download()}" />
@ManagedBean
@SessionScoped
public class MyBean implements Serializable{
//....
public String download{
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
String fileName = "test.txt";
String filePath = "D:\\test.txt"; //externalContext.getRealPath("") + File.separator + fileName;
File file = new File(filePath);
externalContext.setResponseHeader("Content-Type", "text/plain");
externalContext.setResponseHeader("Content-Length", String.valueOf(file.length()));
externalContext.setResponseHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(file);
output = externalContext.getResponseOutputStream();
IOUtils.copy(input, output);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
IOUtils.closeQuietly(output);
IOUtils.closeQuietly(input);
}
facesContext.responseComplete();
return null;
}
//...
}
最佳答案
ICEfaces 有一个奇怪的“feature”,它隐式转换所有标准 JSF <h:commandButton>
到支持 ajax 的命令按钮。但是,无法使用 ajax 下载文件。您需要明确将其关闭。您可以通过嵌套 <f:ajax disabled="true">
在每个按钮的基础上执行此操作.
<h:commandButton value="download" action="#{myBean.download()}" />
<f:ajax disabled="true"/>
</h:commandButton>
另见:
关于Jsf文件下载不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15131582/