PHP 8.9原生Stream API深度优化:如何用3行代码实现GB级文件分块上传与断点续传?
2026/4/29 21:53:00
作为北京某软件公司的项目负责人,我针对大文件传输需求提出以下完整解决方案:
基于贵公司需求,我们决定采用自主研发+部分开源组件整合的方案,主要原因如下:
┌───────────────────────────────────┐ │ 应用层 │ │ ┌─────────┐ ┌─────────┐ │ │ │上传模块 │ │下载模块 │ │ │ └─────────┘ └─────────┘ │ │ │ ├──────────────────────────────────┤ │ 服务层 │ │ ┌─────────┐ ┌─────────┐ │ │ │分片管理 │ │加密服务 │ │ │ └─────────┘ └─────────┘ │ │ ┌─────────┐ ┌─────────┐ │ │ │断点续传 │ │存储适配 │ │ │ └─────────┘ └─────────┘ │ └──────────────────────────────────┘┌───────────────────────────────────┐ │ UI组件层 │ │ ┌───────────────────────┐ │ │ │ 文件选择器 │ │ │ └───────────────────────┘ │ │ ┌───────────────────────┐ │ │ │ 传输队列 │ │ │ └───────────────────────┘ │ │ ┌───────────────────────┐ │ │ │ 进度展示 │ │ │ └───────────────────────┘ │ ├───────────────────────────────────┤ │ 核心逻辑层 │ │ ┌─────────┐ ┌─────────┐ │ │ │分片处理 │ │加密处理 │ │ │ └─────────┘ └─────────┘ │ │ ┌─────────┐ ┌─────────┐ │ │ │断点恢复 │ │多框架适配│ │ │ └─────────┘ └─────────┘ │ └──────────────────────────────────┘@RestController@RequestMapping("/api/upload")publicclassFileUploadController{@PostMapping("/init")publicResponseEntityinitUpload(@RequestParamStringfileId,@RequestParamStringfileName,@RequestParamlongfileSize,@RequestParamintchunkSize){// 初始化上传记录UploadRecordrecord=newUploadRecord();record.setFileId(fileId);record.setFileName(fileName);record.setFileSize(fileSize);record.setChunkSize(chunkSize);record.setStatus(UploadStatus.INIT);uploadService.saveRecord(record);returnResponseEntity.ok().build();}@PostMapping("/chunk")publicResponseEntityuploadChunk(@RequestParamStringfileId,@RequestParamintchunkNumber,@RequestParamMultipartFilechunk){// 处理分片上传uploadService.processChunk(fileId,chunkNumber,chunk);returnResponseEntity.ok().build();}@PostMapping("/complete")publicResponseEntitycompleteUpload(@RequestParamStringfileId,@RequestParamStringfileHash){// 验证并合并文件booleansuccess=uploadService.mergeChunks(fileId,fileHash);if(success){returnResponseEntity.ok().build();}else{returnResponseEntity.status(HttpStatus.CONFLICT).build();}}}@ServicepublicclassUploadServiceImplimplementsUploadService{@OverridepublicvoidprocessChunk(StringfileId,intchunkNumber,MultipartFilechunk){// 1. 校验分片if(!validateChunk(fileId,chunkNumber,chunk)){thrownewBusinessException("分片校验失败");}// 2. 存储分片(加密存储)StringchunkKey=getChunkKey(fileId,chunkNumber);storageService.storeChunk(chunkKey,encryptChunk(chunk));// 3. 更新进度updateProgress(fileId,chunkNumber);}privatebooleanvalidateChunk(StringfileId,intchunkNumber,MultipartFilechunk){// 实现分片校验逻辑returntrue;}privatevoidupdateProgress(StringfileId,intchunkNumber){// 更新数据库中的上传进度UploadRecordrecord=uploadRepository.findByFileId(fileId);record.getCompletedChunks().add(chunkNumber);uploadRepository.save(record);// 同时更新Redis缓存redisTemplate.opsForSet().add("upload:progress:"+fileId,chunkNumber);}}exportdefault{data(){return{files:[],uploadQueue:[],progress:{},chunkSize:5*1024*1024// 5MB}},methods:{handleFileChange(e){constfiles=Array.from(e.target.files);this.prepareUpload(files);},prepareUpload(files){files.forEach(file=>{constfileId=this.generateFileId(file);this.uploadQueue.push({fileId,file,status:'pending',chunks:this.splitFile(file)});});},splitFile(file){constchunks=[];letstart=0;while(start<file.size){constend=Math.min(start+this.chunkSize,file.size);chunks.push({start,end,blob:file.slice(start,end)});start=end;}returnchunks;},asyncstartUpload(){for(constitemofthis.uploadQueue){awaitthis.uploadFile(item);}},asyncuploadFile(item){// 初始化上传awaitthis.$http.post('/api/upload/init',{fileId:item.fileId,fileName:item.file.name,fileSize:item.file.size,chunkSize:this.chunkSize});// 上传分片for(leti=0;i<item.chunks.length;i++){// 检查是否已上传过该分片constisUploaded=awaitthis.checkChunkUploaded(item.fileId,i);if(isUploaded)continue;constformData=newFormData();formData.append('fileId',item.fileId);formData.append('chunkNumber',i);formData.append('chunk',item.chunks[i].blob);awaitthis.$http.post('/api/upload/chunk',formData,{onUploadProgress:progress=>{this.updateProgress(item.fileId,i,progress);}});}// 完成上传awaitthis.$http.post('/api/upload/complete',{fileId:item.fileId,fileHash:awaitthis.calculateHash(item.file)});item.status='completed';},updateProgress(fileId,chunkIndex,progress){if(!this.progress[fileId]){this.progress[fileId]={};}this.progress[fileId][chunkIndex]=progress;}}}// ie8-compat.jsif(!Array.prototype.forEach){Array.prototype.forEach=function(callback,thisArg){varT,k;if(this==null){thrownewTypeError(' this is null or not defined');}varO=Object(this);varlen=O.length>>>0;if(typeofcallback!=="function"){thrownewTypeError(callback+' is not a function');}if(arguments.length>1){T=thisArg;}k=0;while(k<len){varkValue;if(kinO){kValue=O[k];callback.call(T,kValue,k,O);}k++;}};}// File API 兼容if(!window.FileReader){document.write('');}采用树形结构元数据存储:
{"folderId":"123","name":"project","type":"folder","children":[{"fileId":"456","name":"document.pdf","type":"file","size":102400,"chunks":[]},{"folderId":"789","name":"images","type":"folder","children":[]}]}publicvoiddownloadFolder(HttpServletResponseresponse,StringfolderId){// 1. 获取文件夹结构FolderStructurefolder=folderService.getFolderStructure(folderId);// 2. 设置响应头response.setContentType("application/octet-stream");response.setHeader("Content-Disposition","attachment; filename=\""+folder.getName()+".folder\"");// 3. 流式传输文件夹内容try(OutputStreamout=response.getOutputStream()){downloadFolderRecursive(out,folder);}}privatevoiddownloadFolderRecursive(OutputStreamout,FolderStructurefolder){// 写入文件夹标记writeFolderHeader(out,folder);// 处理子文件for(FileItemfile:folder.getFiles()){writeFileHeader(out,file);transferFileContent(out,file);}// 递归处理子文件夹for(FolderStructuresubFolder:folder.getSubFolders()){downloadFolderRecursive(out,subFolder);}// 写入文件夹结束标记writeFolderFooter(out,folder);}客户端: 1. 生成随机对称密钥K 2. 使用K加密文件数据 3. 使用服务端公钥加密K 4. 传输加密后的数据和加密后的K 服务端: 1. 使用私钥解密得到K 2. 使用K解密文件数据 3. 使用配置的存储加密算法(如SM4)重新加密存储 解密下载时逆向此流程基于贵公司需求,我们提供以下授权方案:
买断授权:98万元一次性买断,包含:
资质文件:可提供全套央企合作资料:
实施计划:
稳定性保障:
兼容性测试矩阵:
| 浏览器/OS | Win7 | Win10 | macOS | CentOS |
|---|---|---|---|---|
| IE8 | ✔️ 已验证 | - | - | - |
| Chrome | ✔️ | ✔️ | ✔️ | ✔️ |
| Firefox | ✔️ | ✔️ | ✔️ | ✔️ |
| 360安全浏览器 | ✔️ | ✔️ | - | - |
如需更详细的技术方案或演示,我可安排技术团队进行专项对接。
导入到Eclipse:点南查看教程
导入到IDEA:点击查看教程
springboot统一配置:点击查看教程
NOSQL示例不需要任何配置,可以直接访问测试
选择对应的数据表脚本,这里以SQL为例
up6/upload/年/月/日/guid/filename
支持离线保存文件进度,在关闭浏览器,刷新浏览器后进行不丢失,仍然能够继续上传
支持上传文件夹并保留层级结构,同样支持进度信息离线保存,刷新页面,关闭页面,重启系统不丢失上传进度。
点击下载完整示例