/**
* 文件下载
*/
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(); // 下载excel文件时非常重要,否则可能会报错或者出现空白行!
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");
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(f.getName(),"utf-8"));//建议每次下载文件时,指定输出的文件名编码格式,一般国内设置utf-8
}
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}
Java实现文件下载
最新推荐文章于 2024-10-01 18:51:18 发布