当我单击h:commandButton
它时,它会执行该myBean.dowanlod()
方法,但它不会下载任何文件。这是我在支持 bean 中的方法。没有例外。光标很忙,似乎在等待响应。这种操作是否有任何额外的配置,或者这段代码有什么问题?
<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;
}
//...
}