
问题描述
在某些场景下,我们可能需要对 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(); }
|