前端大文件分片上传

火影  金牌会员 | 2024-6-11 11:04:30 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 545|帖子 545|积分 1635

1.分片上传整体流程



  • 开始上传:前端启动文件分片上传。后端返回唯一标识。
  • 分片上传:获取到上传的文件,然后设置一个固定的分片巨细,将文件切成多个小片,盘算出每一个分片的MD5值(32位)。将每个分片的内容和MD5标识符一同上传至服务器。服务端接收每个分片及相干信息后,通过对每个分片进行校验,来确保分片的完整性。
  • 竣事上传:当分片上传完毕或者前端取消上传时,调用竣事上传接口竣事此次文件上传操纵。竣事上传时,服务端判定是正常竣事或取消上传来决定后续操纵。

2.前端具体流程



  • 开始上传,发送开始上传请求,向服务器转达文件名、文件总巨细、分片总数和切片巨细,获取并保存文件上传的唯一标识符。同时在发送请求前,对上传的文件名进行校验,如果文件名超过最大长度256,则克制发送请求并向用户提示修改文件名称。
  • 分片上传,起首将文件进行切片,调用切片方法时,必要将文件转达给该方法,然后根据文件的巨细来决定每个分片的巨细并切分成多个片段,同时盘算出总切片数,并为每个切片添加从0开始的顺序索引。随后对每个切片盘算出他们的MD5值。最后把这些分片的MD5值和顺序索引保存在浏览器内存中。然后发奉上传数据请求,向服务器发送唯一标识符、分片的顺序索引、分片数据,MD5值和当前分片的巨细。在每个分片发送请求后,如果发送乐成,则将其对应的信息从浏览器内存中删除,并盘算出此时的上传进度,然后发送下一个片段直至最后。如果全部上传乐成,清空浏览器内存。如果请求发生错误,则对该分片再次发送一次上传请求,如果仍然错误,不再上传,调用竣事请求并提示错误原因。
  • 竣事上传,如果文件分片全部乐成上传,向服务器发送竣事请求,转达正常竣事状态码,清空浏览器内存。如果自动取消上传则转达取消请求状态码,同时清空浏览器内存,不再继续上传。
3.部分代码

  1. //文件切片,utils
  2. import SparkMD5 from 'spark-md5'
  3. export async function getChunkList (files) {
  4.         const file = files
  5.         console.log(file);
  6.         const fileSize = file.size // 文件大小
  7.         const fileName = file.name
  8.         let chunkSize = 0;
  9.         if (fileSize <= 5 * 1024 * 1024) { // 0-5M,不分片
  10.                 chunkSize = fileSize;
  11.         } else if (fileSize <= 20 * 1024 * 1024) { // 5-20M,每个分片大小1M
  12.                 chunkSize = 1024 * 1024;
  13.         } else if (fileSize <= 50 * 1024 * 1024) { // 20-50M,每个分片大小2M
  14.                 chunkSize = 2 * 1024 * 1024;
  15.         } else if (fileSize <= 100 * 1024 * 1024) { // 50-100M,每个分片大小4M
  16.                 chunkSize = 4 * 1024 * 1024;
  17.         } else if (fileSize <= 200 * 1024 * 1024) { // 100-200M,每个分片大小6M
  18.                 chunkSize = 6 * 1024 * 1024;
  19.         } else if (fileSize <= 500 * 1024 * 1024) { // 200-500M,每个分片大小10M
  20.                 chunkSize = 10 * 1024 * 1024;
  21.         } else if (fileSize <= 1024 * 1024 * 1024) { // 500M-1G,每个分片大小20M
  22.                 chunkSize = 20 * 1024 * 1024;
  23.         } else { // 1G以上,每个分片大小20M
  24.                 chunkSize = 20 * 1024 * 1024;
  25.         }
  26.         const totalChunks = Math.ceil(fileSize / chunkSize)
  27.         let start = 0
  28.         let end = Math.min(chunkSize, fileSize)
  29.         let index = 0 // 分片索引,从0开始
  30.         const chunks = [] // 存储当前文件的分片信息的数组
  31.         while (start < fileSize) {
  32.                 const chunk = file.slice(start, end)
  33.                 const reader = new FileReader()
  34.                 const promise = new Promise((resolve, reject) => {
  35.                         reader.onload = (e) => { //读取文件分片信息,使用SparkMD5库计算分片的MD5值
  36.                                 const spark = new SparkMD5.ArrayBuffer()
  37.                                 spark.append(e.target.result)
  38.                                 resolve(spark.end())
  39.                         }
  40.                         reader.onerror = (err) => {
  41.                                 reject(err)
  42.                         }
  43.                 })
  44.                 reader.readAsArrayBuffer(chunk)
  45.                 try {
  46.                         const md5 = await promise
  47.                         const chunkInfo = { chunk, md5, index }
  48.                         chunks.push(chunkInfo)
  49.                 } catch (err) {
  50.                         reject(err)
  51.                 }
  52.                 //更新循环起止位置
  53.                 start = end
  54.                 end = Math.min(start + chunkSize, fileSize)
  55.                 index++
  56.         }
  57.         // 将当前文件的分片信息数组存入总的数组中
  58.         return [chunks, totalChunks, fileSize, fileName, chunkSize] // 返回存储所有文件的分片信息的数组
  59. }        
复制代码
  1. async handleUpload () {
  2.                         this.progressState = 'upload'
  3.                         this.wrongNum = 0
  4.                         if (this.fileList.length == 0) { //判断是否添加文件
  5.                                 this.$notify.warning({
  6.                                         title: this.$global.warningMessage.title,
  7.                                         message: this.$global.warningMessage.fileMessage,
  8.                                 });
  9.                                 return
  10.                         }
  11.                         if (this.file.name.length > 256) {
  12.                                 this.$notify.warning({
  13.                                         title: this.$global.warningMessage.title,
  14.                                         message: this.$global.warningMessage.fileNameMessage,
  15.                                 });
  16.                                 return
  17.                         }
  18.                         this.totalSize = this.file.size
  19.                         // 调用getChunkList方法获取分片及相关信息
  20.                         const [chunks, totalChunks, fileSize, fileName, chunkSize] = await getChunkList(this.file.raw)
  21.                         this.totalChunks = totalChunks
  22.                         this.fileSize = fileSize
  23.                         this.fileName = fileName
  24.                         this.chunkList = chunks
  25.                         this.chunkSize = chunkSize
  26.                         console.log(this.chunkList);
  27.                         // 开始上传请求
  28.                         await this.startUpload()
  29.                         // 遍历分片信息数组,取出除文件分片外的其他信息
  30.                         const sessionChunkList = this.chunkList.map(({ chunk, ...rest }) => rest);
  31.                         // 将分片其他信息存入sessionStorage中
  32.                         sessionStorage.setItem("chunkData", JSON.stringify(sessionChunkList));
  33.                         let i = 0;
  34.                         while (i < this.chunkList.length && this.wrongNum < 1) { //对分片数组进行遍历
  35.                                 const chunkInfo = this.chunkList[i];
  36.                                 const res = await this.uploadChunk(chunkInfo); //调用上传分片方法
  37.                                 if (res.data.state == 200) {
  38.                                         const removeInfo = {
  39.                                                 md5: chunkInfo.md5,
  40.                                                 index: chunkInfo.index
  41.                                         }
  42.                                         await this.handleSuccess(removeInfo, chunkInfo) //调用当前分片上传成功处理函数
  43.                                         i++;
  44.                                 } else {   //上传未成功,重新上传一次
  45.                                         const res = await this.uploadChunk(chunkInfo);
  46.                                         this.wrongNum += 1
  47.                                         if (res.data.state == 200) {
  48.                                                 this.wrongNum = 0
  49.                                                 await this.handleSuccess(removeInfo, chunkInfo)
  50.                                                 i++;
  51.                                         } else {  // 重新上传一次后仍未成功
  52.                                                 const state = this.$global.completeUploadState.cancelUpload
  53.                                                 await this.completeUpload(state)
  54.                                                 this.$notify.error({
  55.                                                         title: this.$global.failedMessage.title,
  56.                                                         message: res.data.message
  57.                                                 });
  58.                                                 this.handleClear()
  59.                                                 return
  60.                                         }
  61.                                 }
  62.                         }
  63.                 }
复制代码


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

本帖子中包含更多资源

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

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

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

本版积分规则

火影

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表