问题
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;
}
//...
}
回答1:
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>
See also:
- p:fileDownload not working with h:head
- ICEfaces libary in classpath prevents Save As dialog from popping up on file download
回答2:
Previously I had <h:head>
and <ice:form>
. This file download thing doesn't work with those namespaces. Just using <head>
and <h:form>
resolve the problem. I'm learning JSF, so I have no idea about this. Somehow it works for me.
And I found much better file download tutorial from BalusC's blog. If anyone knows or can guess the reason please give some ideas.
来源:https://stackoverflow.com/questions/15131582/jsf-file-download-doesnt-work