181538-1732184138d091

问题描述

在某些场景下,我们可能需要对 Java 程序中的下载操作进行限速,以控制下载的速度,避免对网络带宽造成过大的压力或者滥用网络资源。

代码实现

思路就是控制某个时间片之内读取文件数据的大小,读取数据写入输出流之后,通过Thread.sleep方法休眠一定时间,达到限速的效果。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
@GetMapping("/download")
public AjaxResult download(@RequestParam String filePath, HttpServletResponse response) throws IOException {
try {
// 获取文件对象
File file = fileService.show(filePath, fileConfig);
if (file == null || !file.exists()) {
return AjaxResult.error("文件不存在");
}

// 格式化下载的文件名,设置响应头
String fileName = file.getName();
String contentType = URLConnection.guessContentTypeFromName(fileName);
fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
response.setContentType(contentType);
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

// 文件内容传输
byte[] bytes = new byte[1024 * 1024];
int byteLength;
try (FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis)) {
while ((byteLength = bis.read(bytes)) != -1) {
response.getOutputStream().write(bytes, 0, byteLength);
Thread.sleep(500);
}
response.getOutputStream().flush();
}
} catch (IOException | InterruptedException e) {
return AjaxResult.error("文件下载出错");
}
return AjaxResult.success();
}