前端大文件断点续传完整实现指南:原理、安全战略与代码实战 ...

打印 上一主题 下一主题

主题 1733|帖子 1733|积分 5199

一、断点续传焦点原理

1.1 技术架构计划

     1.2 焦点流程

     二、前端焦点实现

2.1 文件分片处理

  1. class FileSplitter {
  2.   constructor(file, chunkSize = 5 * 1024 * 1024) {
  3.     this.file = file
  4.     this.chunkSize = chunkSize
  5.     this.totalChunks = Math.ceil(file.size / chunkSize)
  6.     this.currentChunk = 0
  7.   }
  8.   async* getChunk() {
  9.     while (this.currentChunk < this.totalChunks) {
  10.       const start = this.currentChunk * this.chunkSize
  11.       const end = Math.min(start + this.chunkSize, this.file.size)
  12.       const chunk = this.file.slice(start, end)
  13.       yield {
  14.         chunk,
  15.         index: this.currentChunk,
  16.         total: this.totalChunks,
  17.         hash: await this.calculateHash(chunk)
  18.       }
  19.       this.currentChunk++
  20.     }
  21.   }
  22.   async calculateHash(chunk) {
  23.     const buffer = await chunk.arrayBuffer()
  24.     const hashBuffer = await crypto.subtle.digest('SHA-256', buffer)
  25.     return Array.from(new Uint8Array(hashBuffer))
  26.       .map(b => b.toString(16).padStart(2, '0'))
  27.       .join('')
  28.   }
  29. }
复制代码
2.2 上传控制器

  1. class UploadController {
  2.   private file: File
  3.   private chunks: UploadChunk[]
  4.   private concurrentLimit = 3
  5.   private retryLimit = 3
  6.   private uploadedChunks = new Set<number>()
  7.   private progressCallbacks: Function[] = []
  8.   constructor(file: File) {
  9.     this.file = file
  10.     this.initChunks()
  11.     this.loadProgress()
  12.   }
  13.   private initChunks() {
  14.     const splitter = new FileSplitter(this.file)
  15.     this.chunks = Array.from({length: splitter.totalChunks}, (_, i) => ({
  16.       index: i,
  17.       status: 'pending',
  18.       retries: 0
  19.     }))
  20.   }
  21.   async start() {
  22.     const queue = new AsyncQueue(this.concurrentLimit)
  23.     for (const chunk of this.chunks) {
  24.       if (!this.uploadedChunks.has(chunk.index)) {
  25.         queue.add(() => this.uploadChunk(chunk))
  26.       }
  27.     }
  28.     await queue.complete()
  29.     await this.mergeFile()
  30.   }
  31.   private async uploadChunk(chunk: UploadChunk) {
  32.     try {
  33.       const splitter = new FileSplitter(this.file)
  34.       const chunkData = await splitter.getChunk(chunk.index)
  35.       
  36.       const formData = new FormData()
  37.       formData.append('file', chunkData.chunk)
  38.       formData.append('index', chunk.index.toString())
  39.       formData.append('total', chunkData.total.toString())
  40.       formData.append('hash', chunkData.hash)
  41.       const response = await fetch('/api/upload', {
  42.         method: 'POST',
  43.         body: formData
  44.       })
  45.       if (!response.ok) throw new Error('Upload failed')
  46.       
  47.       this.uploadedChunks.add(chunk.index)
  48.       this.saveProgress()
  49.       this.emitProgress()
  50.     } catch (error) {
  51.       if (chunk.retries < this.retryLimit) {
  52.         chunk.retries++
  53.         return this.uploadChunk(chunk)
  54.       }
  55.       throw error
  56.     }
  57.   }
  58. }
复制代码
三、服务端关键实现(Node.js)

3.1 分片接收接口

  1. const express = require('express')
  2. const fs = require('fs-extra')
  3. const multer = require('multer')
  4. const upload = multer({ dest: 'temp/' })
  5. const app = express()
  6. const activeUploads = new Map()
  7. app.post('/api/upload', upload.single('file'), async (req, res) => {
  8.   const { index, total, hash } = req.body
  9.   const fileKey = `${req.file.originalname}-${hash}`
  10.   
  11.   // 校验分片哈希
  12.   const chunkHash = await calculateHash(req.file.path)
  13.   if (chunkHash !== hash) {
  14.     fs.remove(req.file.path)
  15.     return res.status(400).send('Invalid chunk hash')
  16.   }
  17.   // 存储分片信息
  18.   if (!activeUploads.has(fileKey)) {
  19.     activeUploads.set(fileKey, {
  20.       totalChunks: parseInt(total),
  21.       receivedChunks: new Set()
  22.     })
  23.   }
  24.   const uploadInfo = activeUploads.get(fileKey)
  25.   uploadInfo.receivedChunks.add(parseInt(index))
  26.   // 返回已接收分片
  27.   res.json({
  28.     received: Array.from(uploadInfo.receivedChunks)
  29.   })
  30. })
复制代码
3.2 文件归并接口

  1. app.post('/api/merge', async (req, res) => {
  2.   const { fileName, total, hash } = req.body
  3.   const fileKey = `${fileName}-${hash}`
  4.   
  5.   const uploadInfo = activeUploads.get(fileKey)
  6.   if (!uploadInfo || uploadInfo.receivedChunks.size < uploadInfo.totalChunks) {
  7.     return res.status(400).send('Not all chunks received')
  8.   }
  9.   // 合并文件
  10.   const finalPath = path.join('uploads', fileName)
  11.   const writeStream = fs.createWriteStream(finalPath)
  12.   
  13.   for (let i = 0; i < uploadInfo.totalChunks; i++) {
  14.     const chunkPath = path.join('temp', `${fileKey}-${i}`)
  15.     const chunkBuffer = await fs.readFile(chunkPath)
  16.     writeStream.write(chunkBuffer)
  17.     await fs.remove(chunkPath)
  18.   }
  19.   writeStream.end()
  20.   
  21.   // 校验最终文件
  22.   const finalHash = await calculateHash(finalPath)
  23.   if (finalHash !== hash) {
  24.     await fs.remove(finalPath)
  25.     return res.status(500).send('File verification failed')
  26.   }
  27.   activeUploads.delete(fileKey)
  28.   res.sendStatus(200)
  29. })
复制代码
四、安全增强方案

4.1 全链路加密验证

  1. // 前端加密配置
  2. const encryptChunk = async (chunk, publicKey) => {
  3.   const encoder = new TextEncoder()
  4.   const data = encoder.encode(chunk)
  5.   const encrypted = await window.crypto.subtle.encrypt(
  6.     { name: 'RSA-OAEP' },
  7.     publicKey,
  8.     data
  9.   )
  10.   return new Blob([encrypted])
  11. }
  12. // 服务端解密
  13. const decryptChunk = async (encrypted, privateKey) => {
  14.   const buffer = await encrypted.arrayBuffer()
  15.   return crypto.subtle.decrypt(
  16.     { name: 'RSA-OAEP' },
  17.     privateKey,
  18.     buffer
  19.   )
  20. }
复制代码
4.2 安全防护战略

  1. // 客户端防御
  2. const validateFile = (file) => {
  3.   const MAX_SIZE = 10 * 1024 * 1024 * 1024 // 10GB
  4.   const ALLOW_TYPES = ['video/mp4', 'image/png']
  5.   
  6.   if (file.size > MAX_SIZE) throw new Error('文件过大')
  7.   if (!ALLOW_TYPES.includes(file.type)) throw new Error('文件类型不支持')
  8. }
  9. // 服务端防御
  10. const antiVirusScan = async (filePath) => {
  11.   const result = await clamscan.scanFile(filePath)
  12.   if (result.viruses.length > 0) {
  13.     throw new Error('发现恶意文件')
  14.   }
  15. }
复制代码
五、可靠性保障机制

5.1 断点恢复实现

  1. class UploadRecovery {
  2.   static STORAGE_KEY = 'upload_progress'
  3.   
  4.   static saveProgress(fileHash, chunks) {
  5.     const progress = localStorage.getItem(STORAGE_KEY) || {}
  6.     progress[fileHash] = chunks
  7.     localStorage.setItem(STORAGE_KEY, JSON.stringify(progress))
  8.   }
  9.   static loadProgress(fileHash) {
  10.     const progress = JSON.parse(localStorage.getItem(STORAGE_KEY))
  11.     return progress[fileHash] || []
  12.   }
  13.   static clearProgress(fileHash) {
  14.     const progress = JSON.parse(localStorage.getItem(STORAGE_KEY))
  15.     delete progress[fileHash]
  16.     localStorage.setItem(STORAGE_KEY, JSON.stringify(progress))
  17.   }
  18. }
复制代码
5.2 分片校验流程

     六、性能优化方案

6.1 智能分片战略

  1. function calculateChunkSize(fileSize) {
  2.   const MIN_CHUNK = 1 * 1024 * 1024  // 1MB
  3.   const MAX_CHUNK = 10 * 1024 * 1024 // 10MB
  4.   const TARGET_CHUNKS = 100
  5.   
  6.   const idealSize = Math.ceil(fileSize / TARGET_CHUNKS)
  7.   return Math.min(MAX_CHUNK, Math.max(MIN_CHUNK, idealSize))
  8. }
复制代码
6.2 并发控制优化

  1. class AsyncQueue {
  2.   constructor(concurrency = 3) {
  3.     this.pending = []
  4.     this.inProgress = 0
  5.     this.concurrency = concurrency
  6.   }
  7.   add(task) {
  8.     return new Promise((resolve, reject) => {
  9.       this.pending.push({ task, resolve, reject })
  10.       this.run()
  11.     })
  12.   }
  13.   run() {
  14.     while (this.inProgress < this.concurrency && this.pending.length) {
  15.       const { task, resolve, reject } = this.pending.shift()
  16.       this.inProgress++
  17.       task()
  18.         .then(resolve)
  19.         .catch(reject)
  20.         .finally(() => {
  21.           this.inProgress--
  22.           this.run()
  23.         })
  24.     }
  25.   }
  26.   async complete() {
  27.     while (this.pending.length || this.inProgress) {
  28.       await new Promise(resolve => setTimeout(resolve, 100))
  29.     }
  30.   }
  31. }
复制代码
七、完整测试方案

7.1 测试用例计划

测试场景验证目标方法网络中断恢复自动续传能力手动断开网络分片哈希校验数据完整性保障修改分片内容并发压力测试服务器稳固性同时发起100+上传大文件测试内存走漏查抄上传10GB文件 7.2 自动化测试示例

  1. def test_resume_upload():
  2.     # 初始化上传
  3.     file = generate_large_file('1GB.bin')
  4.     response = start_upload(file)
  5.     assert response.status_code == 200
  6.    
  7.     # 中断上传
  8.     interrupt_network()
  9.     upload_chunk()
  10.     assert_last_progress_saved()
  11.    
  12.     # 恢复上传
  13.     restore_network()
  14.     resume_response = resume_upload(file)
  15.     assert_file_complete(resume_response)
复制代码

总结:本文从原理到实践具体讲授了前端断点续传的完整实现方案,包含文件分片、加密传输、进度恢复等焦点技术点,并提供了生产情况可用的代码实现。


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

我爱普洱茶

论坛元老
这个人很懒什么都没写!
快速回复 返回顶部 返回列表