public static boolean download(HttpServletResponse response, String filepath,
HttpServletRequest request) throws Exception {
String path = BasePath.getMyRealPath(request, filepath);
File f = new File(path);
if (!f.exists()) {
System.err.println("error");
return false;
}
FileInputStream fis = new FileInputStream(f);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] buf = new byte[1024];
int len = 0;
String fileName = new String(f.getName().getBytes("UTF-8"), "ISO8859-1");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setContentLength((int) f.length());
OutputStream out = response.getOutputStream();
// 开始循环下载
while (len < f.length()) {
int j = bis.read(buf, 0, 1024);
len += j;
// 将b中的数据写到客户端的内存
out.write(buf, 0, j);
}
// 将写入到客户端的内存的数据,刷新到磁盘
out.flush();
if (null != bis) {
bis.close();
}
if (null != out) {
out.close();
}
return true;
}
Spring MVC下载文件
最新推荐文章于 2023-08-03 08:00:00 发布