public 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(); // 非常重要
//response.setCharacterEncoding("utf-8");
if (isOnLine) { // 预览
URL u = new URL("file:///" + filePath);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition", "inline; filename=" + f.getName());
} else { //下载
response.setContentType("application/x-msdownload");
String fileName=java.net.URLEncoder.encode(f.getName(),"UTF-8");
response.setHeader("Content-Disposition", "attachment; filename="+fileName);
}
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}
参数isOnLine=true是预览,isOnLine=false是下载。