vue 大文件分片上传

<template>
</template>

<script>
  import axios from 'axios'
  export default {
    name: 'YunShuBigFileUpload',
    props: {
      fileId: { // 上传 type="file"的id
        type: String
      },
      UploadComplete: { // 完成时执行函数
        type: Function
      },
      ChunkSize: { // 切片大小  单位时MB
        type: Number
      },
      url: { //上传地址
        type: String
      },
      md5: { // 文件的md5值
        type: String
      },
      UploadProgress: { // 上传进度
        type: Function
      }
    },
    watch: {
      md5() {
        this.myMd5 = this.md5
      }
    },
    data() {
      return {
        uploadFile: {
          chunk: 0,
          isLastChunk: false,//是否最后一片文件
          fileName: ''//文件名称
        },
        myMd5: '',
      }
    },
    created() {
      this.myMd5 = this.md5
    },
    methods: {
      chunksFile() {
        // this.fileId : '上传的input元素id'   例如 #input-file-upload
        let file = document.querySelector(this.fileId).files[0], //需要上传的文件
          chunkLength = 0; //文件分片后的长度
        this.uploadFile.fileName = file.name;
        if (file.size > 1024 * 1024 * this.ChunkSize) {
          chunkLength = Math.ceil(file.size / (1024 * 1024 * this.ChunkSize));
        } else {
          chunkLength = 1
        }
        this.uploadFile.chunk === chunkLength - 1 ? this.uploadFile.isLastChunk = true : false;
        let fm = new FormData();
        fm.append('md5', this.myMd5);
        fm.append('size', file.size);
        fm.append('chunk', this.uploadFile.chunk);
        fm.append('chunks ', chunkLength);
        fm.append('fileName ', this.uploadFile.fileName);
        fm.append('file', file.slice(this.uploadFile.chunk * 1024 * 1024 * this.ChunkSize, (this.uploadFile.chunk + 1) * 1024 * 1024 * this.ChunkSize));
        //通过ajax上传分片文件内容
        axios.post(this.url, fm).then((res) => {
          if (res.status == 200) {
            //上传成功,分片加一,上传下一片文件
            this.uploadFile.chunk++
            //上传完最后一片后传输结束
            const pr = parseInt((this.uploadFile.chunk + 1) / chunkLength * 100)
            this.UploadProgress(pr)
            if (this.uploadFile.isLastChunk) {
              this.UploadComplete()
            } else {
              //递归调用上传下一片
              this.chunksFile();
            }
          }
        }).catch((error) => {
          console.log(error)
            this.$Message.warning('上传失败!')
        });
      }
    }
  }
</script>

<style>
</style>

需要和下一篇的《根据文件内容生成md5》配合使用

打工者联盟为了抵抗996、拖欠工资、黑心老板、恶心公司,让我们组成打工者联盟。客观评价自己任职过的公司情况,为其他求职者竖起一座引路的明灯。https://book.employleague.cn/

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值