@GetMapping("/download") public void download(@RequestParam String path, HttpServletRequest request, HttpServletResponse response) throws IOException { Path downloadFile = Paths.get(path); if (!Files.exists(downloadFile)) { response.setStatus(HttpStatus.NOT_FOUND.value()); return; } long fromPos = 0; long downloadSize = Files.size(downloadFile); if (request.getHeader("Range") != null) { response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); String[] ary = request.getHeader("Range").replaceAll("bytes=", "").split("-"); fromPos = Long.parseLong(ary[0]); downloadSize = (ary.length < 2 ? downloadSize : Long.parseLong(ary[1])) - fromPos; } response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); response.setContentLengthLong(downloadSize); response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", downloadFile.getFileName().toString())); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("Content-Range", String.format("bytes %s-%s/%s", fromPos, (fromPos + downloadSize), Files.size(downloadFile))); try (FileChannel inChannel = FileChannel.open(downloadFile); WritableByteChannel outChannel = Channels.newChannel(response.getOutputStream())) { while (downloadSize > 0) { long count = inChannel.transferTo(fromPos, downloadSize, outChannel); if (count > 0) { fromPos += count; downloadSize -= count; } } } }
spring boot断点续传
最新推荐文章于 2024-08-17 11:05:49 发布