项目初期说的是下载文件的大小大概就是几十M,没想到越来越大,还有十几个G的可能,之前写的下载功能直接就一直转圈圈,F12看到请求一直是挂起状态,持续了将近一分钟:
然后突然变成404:
整改之前的代码:
/**
* 文件下载
* @param response 请求响应
* @param sourcePath 下载目标文件路径
* @param name 下载后的文件名
* @return 是否下载成功
* @throws Exception
*/
public static boolean down(HttpServletResponse response,String sourcePath, String name) throws Exception {
OutputStream out = null;
try {
if(sourcePath != null){
byte[] byteArray = null;
response.setHeader("Content-Disposition", "attachment;filename=" + name + " ");
InputStream input = new FileInputStream(new File(sourcePath+name));
int lenth = input.available();
byteArray = new byte[lenth];
input.read(byteArray);
input.close();
out = response.getOutputStream();
out.write(byteArray);
out.flush();
out.close();
}
} catch (Exception ex) {
return false;
} finally {
if (out != null)
out.close();
}
return true;
}
使用缓存流(BufferedInputStream和BufferedOutputStream)对下载接口进行整改以满足大文件下载的需求:
/**
* 使用缓存流进行超5G大文件下载
* @param response 响应
* @param path 要下载的文件的绝对路径
* @throws Exception
*/
private void downloadFile(HttpServletResponse response, String path) throws Exception {
File file = new File(path);
if (!file.isFile()) {
throw new Exception("文件不存在");
}
String filename = path.substring(path.lastIndexOf(File.separator));
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
try (FileInputStream fileInputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream())) {
//根据服务器配置和下载文件大写合理调整
byte[] buffer = new byte[1024*100];
int n = bufferedInputStream.read(buffer);
while(n != -1){
bufferedOutputStream.write(buffer);
n = bufferedInputStream.read(buffer);
}
bufferedInputStream.close();
bufferedOutputStream.close();
} catch(Exception e){
e.printStackTrace();
}
}
接口调整后别忘了检查以下配置:
①spring boot对下载文件大小限制的配置项;
②如果项目使用nginx,检查下nginx文件传输大小限制的配置项。