Jsf文件下载不起作用 [英] Jsf file download doesn't work
问题描述
当我点击 h:commandButton
时,它会执行 myBean.dowanlod()
方法,但它没有' t下载任何文件。
这是我在backing bean中的方法。没有例外。光标变得忙碌,似乎在等待响应。是否有此类操作的其他配置或此代码是否有任何错误?
When I click the h:commandButton
it execute the myBean.dowanlod()
method, but it doesn't download any files.
Here is my methods in the backing bean. No exceptions. Cursor gets busy and seems like waiting for a response. Are there any additional configurations for this kind of operations or is there any wrong with this code?
<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有一个奇怪的功能它隐式地将所有标准JSF < h:commandButton>
转换为启用ajax的命令按钮。但是,使用ajax下载文件是不可能的。您需要明确地将其关闭。您可以通过嵌套< f:ajax disabled =true>
来按每个按钮执行此操作。
ICEfaces has the strange "feature" that it implicitly converts all standard JSF <h:commandButton>
to ajax-enabled command buttons. However, it's not possible to download files using ajax. You need to explicitly turn it off. You can do that on a per-button basis by nesting a <f:ajax disabled="true">
.
<h:commandButton value="download" action="#{myBean.download()}" />
<f:ajax disabled="true"/>
</h:commandButton>
参见:
- p:fileDownload不使用h:head
- ICEfaces libary in classpath阻止另存为对话框弹出文件下载
- p:fileDownload not working with h:head
- ICEfaces libary in classpath prevents Save As dialog from popping up on file download
See also:
这篇关于Jsf文件下载不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!