// 下载其实非常简单,只要如下处理,就不会发生问题。 public static void downLoad(String filePath, HttpServletResponse response,
boolean isOnLine) throws Exception {
File f = new File(filePath);
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0; response.reset(); // 非常重要
if (isOnLine) { // 在线打开方式
URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename="
+ f.getName());
// 文件名应该编码成UTF-8
} else { // 纯下载方式
response.setContentType("application/x-msdownload;charset=gbk");
response.setHeader("Content-Disposition", "attachment; filename="
+ f.getName());
}
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}
boolean isOnLine) throws Exception {
File f = new File(filePath);
if (!f.exists()) {
response.sendError(404, "File not found!");
return;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte[] buf = new byte[1024];
int len = 0; response.reset(); // 非常重要
if (isOnLine) { // 在线打开方式
URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename="
+ f.getName());
// 文件名应该编码成UTF-8
} else { // 纯下载方式
response.setContentType("application/x-msdownload;charset=gbk");
response.setHeader("Content-Disposition", "attachment; filename="
+ f.getName());
}
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}
try {
String fileName="D:\\temp\\images\\products\\" + this.id + ".xls";
logger.debug("file name=" + fileName);
ByteArrayOutputStream baos=this.serviceLocator.getFileService().downloadFile(fileName); //调用Service方法,获得文件的ByteArrayOutputStream
HttpServletResponse response=FacesUtils.getServletResponse();
response.setHeader("Content-disposition", "attachment; filename=" + id+ ".xls" ); //不是内嵌显示(inline),而是作为附件下载
response.setContentLength(baos.size());
ServletOutputStream sos=response.getOutputStream();
baos.writeTo(sos);
baos.close();
sos.flush();
} catch (IOException ex) {
logger.debug(ex);
}
}
<h:commandLink actionListener="#{productBean.downloadAction}" styleClass="highLightLink">
<h:outputText value="download"/>
<f:param name="productId" value="#{productBean.id}"/>
</h:commandLink>出处http://blog.csdn.net/gohands/archive/2008/02/15/2096713.aspx