Spring Boot 实现文件分段上传与断点续传及分片下载示例
针对大文件传输场景,本文详细解析基于 Spring Boot 的文件分段上传、断点续传机制以及后端合并策略。同时涵盖利用 HTTP Range 头部实现的分片下载代码,旨在提供一套稳定、高效的大文件处理解决方案。
依赖配置
在开始实现前,需要在 Maven 项目中引入 Commons IO 和 Commons FileUpload 库以简化文件流操作,同时引入 Apache HttpClient 用于模拟请求(如需服务端代理下载)。以下为基础依赖配置:
<!-- JDK提供的关于文件上传工具 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.10.0</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
<!-- Apache提供的HTTP客户端与服务端 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.14</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>前端 WebUploader 配置
前端采用 WebUploader 组件进行文件分片与上传控制。主要配置包括启用 chunked 开启分片模式,设置 threads 控制并发线程数,并指定服务端接收地址。当用户点击或拖拽文件时,自动按分片大小切割文件并依次调用接口。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>webuploader</title>
</head>
<!--引入CSS-->
<link rel="stylesheet" type="text/css" href="https://cdn.bootcss.com/webuploader/0.1.1/webuploader.css" rel="external nofollow" >
<style>
#upload-container, #upload-list{width: 500px; margin: 0 auto; }
#upload-container{cursor: pointer; border-radius: 15px; background: #EEEFFF; height: 200px;}
#upload-list{height: 800px; border: 1px solid #EEE; border-radius: 5px; margin-top: 10px; padding: 10px 20px;}
#upload-container>span{widows: 100%; text-align: center; color: gray; display: block; padding-top: 15%;}
.upload-item{margin-top: 5px; padding-bottom: 5px; border-bottom: 1px dashed gray;}
.percentage{height: 5px; background: green;}
.btn-delete, .btn-retry{cursor: pointer; color: gray;}
.btn-delete:hover{color: orange;}
.btn-retry:hover{color: green;}
</style>
<!--引入JS-->
<body>
<div id="upload-container">
<span>点击或将文件拖拽至此上传</span>
</div>
<div id="upload-list">
<!-- <div class="upload-item">
<span>文件名:123</span>
<span data-file_id="" class="btn-delete">删除</span>
<span data-file_id="" class="btn-retry">重试</span>
<div class="percentage"></div>
</div> -->
</div>
<button id="picker" style="display: none;">点击上传文件</button>
</body>
<script src="http://lib.sinaapp.com/js/jquery/2.0.2/jquery-2.0.2.min.js"></script>
<script src="https://cdn.bootcss.com/webuploader/0.1.1/webuploader.js"></script>
<script>
$('#upload-container').click(function(event) {
$("#picker").find('input').click();
});
var uploader = WebUploader.create({
auto: true,// 选完文件后,是否自动上传。
swf: 'https://cdn.bootcss.com/webuploader/0.1.1/Uploader.swf',// swf文件路径
server: 'http://www.test.com/zyb.php',// 文件接收服务端。
dnd: '#upload-container',
pick: '#picker',// 内部根据当前运行是创建,可能是input元素,也可能是flash. 这里是div的id
multiple: true, // 选择多个
chunked: true,// 开起分片上传。
threads: 5, // 上传并发数。允许同时最大上传进程数。
method: 'POST', // 文件上传方式,POST或者GET。
fileSizeLimit: 1024*1024*100*100, //验证文件总大小是否超出限制, 超出则不允许加入队列。
fileSingleSizeLimit: 1024*1024*100, //验证单个文件大小是否超出限制, 超出则不允许加入队列。
fileVal:'upload', // [默认值:'file'] 设置文件上传域的name。
});
uploader.on('fileQueued', function(file) {
// 选中文件时要做的事情,比如在页面中显示选中的文件并添加到文件列表,获取文件的大小,文件类型等
console.log(file.ext) // 获取文件的后缀
console.log(file.size) // 获取文件的大小
console.log(file.name);
var html = '<div class="upload-item"><span>文件名:'+file.name+'</span><span data-file_id="'+file.id+'" class="btn-delete">删除</span><span data-file_id="'+file.id+'" class="btn-retry">重试</span><div class="percentage '+file.id+'" style="width: 0%;"></div></div>';
$('#upload-list').append(html);
});
uploader.on('uploadProgress', function(file, percentage) {
console.log(percentage * 100 + '%');
var width = $('.upload-item').width();
$('.'+file.id).width(width*percentage);
});
uploader.on('uploadSuccess', function(file, response) {
console.log(file.id+"传输成功");
});
uploader.on('uploadError', function(file) {
console.log(file);
console.log(file.id+'upload error')
});
$('#upload-list').on('click', '.upload-item .btn-delete', function() {
// 从文件队列中删除某个文件id
file_id = $(this).data('file_id');
// uploader.removeFile(file_id); // 标记文件状态为已取消
uploader.removeFile(file_id, true); // 从queue中删除
console.log(uploader.getFiles());
});
$('#upload-list').on('click', '.btn-retry', function() {
uploader.retry($(this).data('file_id'));
});
uploader.on('uploadComplete', function(file) {
console.log(uploader.getFiles());
});
</script>
</html>上传数据格式说明
前端在发送每个分片时,会携带特定的表单信息供后端识别。关键参数包括:
id: 文件唯一标识(如 WU_FILE_1);
name: 原始文件名;
chunks: 总分片数量;
chunk: 当前分片的索引编号(从 0 开始);
upload: 实际的二进制文件数据。
#前台传输文件的表单信息 id: WU_FILE_1 文件ID name: 录制_2021_03_19_08_52_06_801.mp4 #文件名 type: video/mp4 #类型 lastModifiedDate: Fri Mar 19 2021 08:52:22 GMT+0800 (中国标准时间) size: 45711359 #大小 chunks: 9 #总分片数 chunk: 0 #当前分片的编号 upload: (binary)
后端分段上传与断点续传逻辑
后端接收接口的核心思路是:首先判断当前分片是否已存在(通过检查临时目录下的 {文件名}_{分片号}),若不存在则写入;若是最后一个分片(chunk == chunks - 1),则执行所有分片的合并操作,并清理临时文件。
@RequestMapping("/update")
public String update(HttpServletRequest request,MultipartFile files,
@RequestParam("chunks") Integer chunks,
@RequestParam("chunk") Integer chunk,
@RequestParam("name") String name){
//根据原理,需要准备写的流os,写的位置locate,
//分片临时位置tempLocate,当前分片数chunk[表单获取],总分片数chunks[表单获取],
//文件名称name[表单获取],临时分片名称tempName
String tempName = null, locate="E:\\file",tempLocate="E:\\file\\temp";
BufferedOutputStream os = null;
try {
//----------------参数判断----------------
if (name == null || chunk == null || chunks == null){
log.error("参数未获取到");
return "";
}
if (files == null){
log.error("数据上传失败");
return "";
}
//----------------断点续传----------------
tempName = name+"_"+chunk;
File assest = new File(tempLocate,tempName);
//文件不存在再写,实现断点续传
if (!assest.exists()){
files.transferTo(assest);
}
//----------------合并数据----------------
long curTime = System.currentTimeMillis();
if (chunk == chunks-1){
File file = new File(locate,name);
os = new BufferedOutputStream(new FileOutputStream(file));
for (int i = 0; i < chunks; i++) {
File temp = new File(tempLocate,name+"_"+i);
while (!temp.exists()){
//if (System.currentTimeMillis() - curTime > waitTime){
// return "合并时过长,请重新上传文件";
//}
Thread.sleep(100);
}
byte[] bytes = FileUtils.readFileToByteArray(temp);
os.write(bytes);
os.flush();
temp.delete();
}
os.flush();
return "上传文件成功";
}
}catch (Exception e) {
log.warn("文件上传出错");
return "文件上传错误,等待网页维护人员进行维护";
} finally {
try {
if (os != null){
os.close();
}
}catch (IOException e){
log.info("文件上传流关闭失败");
}
}
return "null";
}分片下载实现
分片下载依赖 HTTP 协议的 Range 请求头。客户端发送请求时告知期望读取的字节范围(格式:bytes=start-end),服务器解析该头部,使用 RandomAccessFile 定位文件指针,仅返回对应区间的二进制流,并设置相应的响应头以告知客户端这是部分内容。
@RequestMapping("/download")
public void download(HttpServletRequest request, HttpServletResponse response){
File file = new File("E:\\file\\测试.mp4");
if (!file.exists()){
return;
}
//-----------------设置参数-----------------
Long begin = 0l,//开始读取位置
fileSize=file.length(),//内容长度
end = fileSize - 1,//结束读取位置
curSize = 0l;//本次读取分片的大小
BufferedOutputStream os = null;//写流
RandomAccessFile is = null;//读流
String fileName;//文件名称
try {
//-----------------设置文件的基础参数-----------------
//获取文件名称
fileName = file.getName();
String range = request.getHeader("Range");
//判断range:bytes=XXX-XXX
if (range != null && range.contains("bytes=") && range.contains("-")){
range = range.replaceAll("bytes=","").trim();
String[] split = range.split("-");
if (!StringUtils.hasLength(split[0])){
//特殊情况1:-XXX
end = Long.parseLong(split[1]);
}else if (split.length == 1){
//特殊情况2:XXX-
begin = Long.parseLong(split[0]);
}else if (split.length == 2){
//理想情况
begin = Long.parseLong(split[0]);
end = Long.parseLong(split[1]);
if (end > fileSize - 1){
end = fileSize - 1;
}
}
}else {
end = fileSize - 1;
}
curSize = end - begin + 1;
//-----------------前端响应头设置-----------------
//设置为下载
response.setContentType("application/x-download");
//设置下载文件的信息
response.addHeader("Content-Disposition",
"attachment;filename="+new String(fileName.getBytes(),"ISO8859_1"));
//支持分片下载
response.setHeader("Accept-Ranges","bytes");
//Content-Type 表示资源类型,如:文件类型
response.setHeader("Content-Type", request.getServletContext().getMimeType(fileName));
//设置文件大小
response.setHeader("Content-Length",String.valueOf(curSize));
//设置响应数据量:bytes [下载开始位置]-[结束位置]/[文件大小]
response.setHeader("Content-Range","bytes "+begin+"-"+end+"/"+fileSize);
//设置专门的响应类型
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
//自定义一些文件头
response.setHeader("fileSize", String.valueOf(fileSize));
response.setHeader("fileName", new String(fileName.getBytes(),"ISO8859_1"));
//-----------------读写文件-----------------
os = new BufferedOutputStream(response.getOutputStream());
is = new RandomAccessFile(file,"r");
byte[] buffer = new byte[1024];
int len = 0;
Long sum = 0l;//累计添加的流
//跳过已经获取的
is.seek(begin);
while (sum<curSize){
int readSize = buffer.length;
if ((curSize-sum)<readSize){
readSize = (int) (curSize-sum);
}
if ((len = is.read(buffer,0,readSize))==-1){
break;
}
os.write(buffer,0,len);
sum+=len;
}
log.info("下载成功");
} catch (Exception e) {
log.warn("下载出现错误");
}finally {
if (os != null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}注意事项与总结
虽然前端支持分片下载,但在浏览器环境下直接管理分片的本地存储与合并较为复杂,且容易引发安全性与用户体验问题。因此,建议在后端实现完整的文件读取与流式传输,而非在前端手动下载所有分片后再合并。此外,上述代码展示了核心的 I/O 操作逻辑,在实际生产环境中,还需考虑并发冲突处理、临时文件清理策略以及更完善的异常捕获机制。
以上就是 Spring Boot 实现文件分段上传、断点续传及分片下载的详细内容,更多关于 Spring Boot 文件传输优化的资料请关注本站其它相关文章!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









