大文件前端简单分段上传

使用vue和element-ui el-upload

<el-upload action="#" :http-request='splitFile'></el-upload>

fileNum:1;
methods:{
  splitFile(file){
    const reader=new FileReader();
    reader.readAsArrayBuffer(file);
    let fileName=file.name;
    const blockSize=4*1024*1024;
    reader.addEventListener('load', async (e)=>{
      let nextSize=Math.min(this.fileNum*blockSize,file.size);
      if(file.size==nextSize){
        const percent=nextSize/file.size;
        const slice=e.target.result;
        try{ await this.uploadFile(slice,percent,fileName); }catch(err){ await this.uploadFile(slice,percent,fileName);  }//上传错误,重新上传          
      }
      while(file.size>nextSize){ 
        nextSize=Math.min(this.fileNum*blockSize,file.size);
        const percent=(blockSize*this.fileNum)/file.size;
        const slice=e.target.result.slice((this.fileNum-1)*blockSize,nextSize);
        try{ await this.uploadFile(slice,percent,fileName); }catch(err){ await this.uploadFile(slice,percent,fileName);  }//上传错误,重新上传 
        this.fileNum++;
      }
    });
  },
  uploadFile(slice,percent,fileName){
    let sliceOrder=this.fileNum-1;//上传的文件片段从0开始
    let fName=fileName.split(',');
    let sliceName=fname[0]+sliceOrder+'.'+fname[1];
    let sfile=new File([slice],sliceName);//文件片段转为 file类型
    const form=new formData();
    form.append('file',sfile);
    form.append('sliceOrder',sliceOrder);
    form.append('fileName',fileName);
     return uploadFile(form)
  }
}

 

总结:

1 readAsArrayBuffer 得到的数据是arrayBuffer类型的,需要转为file    new File([file],fileName)

2 上传的代码片段如果太大,会出现  failed to load response data,看不到请求体和返回数据,本人测试谷歌浏览器设置为5M不行,设置为4M就可以正常显示了(blockSize)

 

posted on 2021-12-10 17:38  半夏微澜ぺ  阅读(414)  评论(0编辑  收藏  举报