做了功能允许用户下载项目系统中上传的文件,
下载倒是没有问题,但是后台会因为不同后缀的文件,偶尔会异常,但是不影响下载。
目前测试,导出xlsx,txt没问题,其他类型文件都会报异常,说什么主动断开了一个连接之类的异常,但是不影响下载。
百思不得其解~~~。
核心代码如下
public static void downloadFile(String fileFullName) throws IOException {
HttpServletResponse response = getResponse();
File f = new File(fileFullName);
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.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(f.getName(), "utf-8"));
OutputStream out = response.getOutputStream();
while ((len = br.read(buf)) > 0)
out.write(buf, 0, len);
br.close();
out.close();
}