我正在尝试从JSF页面下载文件,但在检查浏览器中的content-length
时,我发现它为0。
这是我在托管Bean中的方法:
public void downloadFile() throws IOException {
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
File file = new File("C:\\data\\contacts.doc");
response.reset();
response.setHeader("Content-Disposition", "attachment;filename=contacts.doc");
response.setContentLength((int) file.length());
response.setContentType("application/octet-stream");
OutputStream out = response.getOutputStream();
try {
FileInputStream input = new FileInputStream(file);
byte[] buffer =new byte[2048];
int offset = 0;
int byteRead =0;
while ((offset= input.read(buffer))!= -1 ) {
offset += byteRead ;
out.write(buffer,0,offset);
}
out.flush();
out.close();
input.close();
FacesContext.getCurrentInstance().getResponseComplete();
} catch (IOException err) {
err.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException err) {
err.printStackTrace();
}
}
这是xhtml页面:
<h:form>
<h:commandButton value="Download" action="#{helloBean.downloadFile}" />
</h:form>
我正在使用Eclispe + Glassfish 4。
答案 0 :(得分:0)
我是扩展问题,我把.docx代替.doc(.doc不再存在)