Vue2大文件分片上传

 <input type="file" @change="handleFileUpload" accept=".mp4" ref="fileInput" />

 data:

chunkSize: 1024 * 1024 * 1, // 每个切片的大小(这里设置为1MB)

fileIndex: 0,

fileChunks: [],

totoleNum: 0, // 总切片数

catalogueInfo: {}, // 目录详情

async handleFileUpload(e) {
      this.file = e.target.files[0];
      console.log(this.file)
      // 文件格式大小判断处理
      const isJPG = e.target.files[0].type === 'video/mp4'
      if (!isJPG) {
        this.$message.error('上传视频必须是mp4文件')
        return
      }
      const isLt2M = Math.ceil(e.target.files[0].size / this.chunkSize)
      this.totoleNum = isLt2M

      this.splitFileIntoChunks(e.target.files[0])

      this.videoUploadFun()
    },
    // 将文件切割为多个切片
    splitFileIntoChunks(file) {
      let that = this
      const fileSize = file.size
      that.fileChunks = [];
      for (let i = 0; i < that.totoleNum; i++) {
        const start = i * that.chunkSize;
        const end = Math.min(start + that.chunkSize, fileSize);
        const chunk = file.slice(start, end);
        that.fileChunks.push(chunk);
      }
      console.log(that.fileChunks)
    },
/**
     * 分片上传接口
     * */
    videoUploadFun() {
      const that = this
      const formData = new FormData();
      formData.append('file', this.fileChunks[this.fileIndex]);
      formData.append('totalPage', this.totoleNum);
      formData.append('page', this.fileIndex + 1);
      formData.append('fileName', this.file.name);
      formData.append('fileExt', 'mp4');
      formData.append('size', this.file.size);
      videoUpload(formData).then(res => {
        that.fileIndex++;
        if (that.fileIndex < that.totoleNum) {
          that.videoUploadFun()
        } else {
          // 所有切片上传完成,进行合并或其他处理
          that.mergeChunks(res)
        }
      })
    },
    // 切片合并或其他处理
    mergeChunks(e) {
      console.log(e)
      if (e.status === '1') {
        return this.$message.error('上传报错')
      }
      this.$message.success('上传成功')
      this.pram.url = e.filePath
      getCourseUrl(e.filePath).then(res => {

      })
      // 所有切片上传完成后,进行切片合
      // 其他处理逻辑
      // 所有切片上传完成,清理数据
      // that.fileIndex = 0
      // that.totalChunks = 0
      // that.file = null
    },

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值