vue+element分段上传大文件

上传大文件需要跟后台配合,准备你的header

  <p>2.上传商品信息</p>
               <div>
              <el-upload
                class="upload-demo"
                drag
                ref="uploadImg"
                action="https://jsonplaceholder.typicode.com/posts/"
                :on-error="uploadFalseImg"
                :on-success="uploadSuccessImg"
                :on-change="handleChangeImg"
                :file-list="fileListImg"
                :headers="headerObj"
                :auto-upload="false"
                :before-upload="beforeAvatarUploadImg"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">将压缩包拖到此处,或<em>点击上传</em></div>
                <div class="el-upload__tip" slot="tip">只能压缩包文件</div>
              </el-upload>
              <div style="width:50%" v-show="isPercentage">
                <el-progress :text-inside="true" :stroke-width="20" :percentage="percentage" :format="format" status="success"></el-progress>
              </div>
            </div>

这里做的是点击上传

 ImportExcelImg() {
      console.log(this.$refs.uploadImg.uploadFiles);
      if (this.$refs.uploadImg.uploadFiles.length == 0) {
        this.$message.error('请先选择文件');
        return;
      } else {
        let file = this.$refs.uploadImg.uploadFiles[0].raw;
        // file.name = file.name.split('.')[0];
        // console.log(file);
        let time = this.getDate();
        this.uploadFile(file.name, file, time);
      }
    },
  

> //element 上传的方法
	//上传前需要验证当前的文件格式		
       handleChangeImg(file, fileList) {
      let regEn = /[`~!@#$%^&*()_+<>?:"{},\/;'[\]]/im,
        regCn = /[·!#¥(——):;“”‘、,|《。》?、【】[\]]/im;
      if (this.$refs.uploadImg.uploadFiles.length > 1) {
        this.$message({
          message: '上传一个文件只能!',
          type: 'error'
        });
        this.fileListImg = [];
        return;
      } else if (regEn.test(file.name) || regCn.test(file.name)) {
        this.$message({
          message: '文件不能包含特殊字符',
          type: 'error'
        });
        this.fileListImg = [];
        return false;
      } else {
        let str = file.name.substr(-4).split('.');
        console.log(str);
        const extension = str[str.length - 1] === 'zip';
        if (!extension) {
          this.$message({
            message: '上传文件只能是 zip 格式!',
            type: 'error'
          });
          this.fileListImg = [];
        }
        return extension;
      }
    },
    // 上传图片压缩文件
    uploadFalseImg() {
      this.$message.error('上传失败');
      this.fileList = [];
    },
    uploadSuccessImg(res, file) {
      if (res.code == 0) {
        this.result = res.data;
        
        this.$message.success('上传成功');
      } else {
        this.$message.error(res.message);
        this.fileListImg = [];
      }
    },
    beforeAvatarUploadImg(file) {
      const extension = file.name.split('.')[1] === 'zip';
      if (!extension) {
        this.$message({
          message: '上传文件只能是zip格式!',
          type: 'error'
        });
      }
      return extension;
    },
    // 分批上传
    uploadFile(filepath, file, time) {
      var filesize = file.size;
      var filecount = filesize / this.shardSize; //计算出可以分成几块
      var i = localStorage.getItem(filepath);
      i = i != null && i != '' ? parseInt(i) : 0;
      var isEnd = 0;
      let stringName = time + file.name;
      console.log(stringName);
      if (i < filecount) {
        //新建一个FormData对象
        var formData = new FormData(); //++++++++++
        var blobfile;
        if (filesize - i * this.shardSize > this.shardSize) {
          blobfile = file.slice(i * this.shardSize, (i + 1) * this.shardSize);
        } else {
          //代表是最后一此了
          blobfile = file.slice(i * this.shardSize, filesize);
          isEnd = 1;
        }
        formData.append('chunk', i); //++++++++++当前文件块
        formData.append('fileName', stringName); //文件名uuid
        formData.append('fileData', blobfile);
        formData.append('isEnd', isEnd); //+++++++++是否结束
        if (i < filecount) {
          this.$http({
            url: '/goodsInfo/updateGoodsPictures',
            // url: '/sysoss/bigFile',
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            contentType: 'application/json'
          })
            .then(res => {
              console.log(res);
              localStorage.setItem(filepath, i + 1);
              var rs = filecount <= 0 ? 0 : Math.round(((i + 1) / Math.ceil(filecount)) * 10000) / 100.0;
              this.percentage = rs;
              if (res.data.data.updateEnd == 1) {
                this.$message.success('上传完毕');
                this.isPercentage = false;
                this.$refs.uploadImg.uploadFiles = [];
              }
              // console.log('进度百分比:' + rs);
              // if (rs === 100) {
              //   this.creatFrom.attachment_url = res.data.data;
              // }
              this.uploadFile(filepath, file, time); //递归调
            })
            .catch(err => {
              console.log('上传错误');
              console.log(err);
            });
        }
      } else {
        //上传完成后,则将对应的localStorage移除掉
        localStorage.removeItem(filepath);
      }
    },


版权声明:本文为dacksir原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。