@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断点续传
最新推荐文章于 2025-04-02 07:23:35 发布
本文介绍了一个使用Spring MVC实现的文件下载API。该API支持HTTP范围请求,能够处理从指定位置开始的部分文件下载,并正确设置HTTP响应头以允许客户端续传或断点下载。通过示例代码展示了如何使用Java NIO进行高效的数据传输。
1322

被折叠的 条评论
为什么被折叠?



