vue-simple-uploader超大文件分片秒传和断点续传

版权声明:所有原创文章未经本人同意不得随意转载,谢谢 https://blog.csdn.net/tangcc110/article/details/85226045

实例:

<!--属性表单-->
<el-dialog title="导入zip压缩文件" :visible.sync="importZipFile_dialog" width="900px" v-loading="myloading">
  <el-form label-position="right">

    <uploader :options="options" class="uploader-example" :autoStart="false"
              @file-added="fileAdded" @file-progress="onFileProgress" @file-success="onFileSuccess" @file-error="onFileError">
      <uploader-unsupport></uploader-unsupport>
      <uploader-drop>
        <!--<p>拖动文件到此处上传</p>-->
        <uploader-btn :single="true">选择文件</uploader-btn>
        <!--<uploader-btn :attrs="attrs">选择图片</uploader-btn>-->
        <!--<uploader-btn :directory="true">选择文件夹</uploader-btn>-->
      </uploader-drop>
      <uploader-list ref="uploader_list">
      </uploader-list>
    </uploader>

  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="importZipFile_dialog = false">关 闭</el-button>
  </div>
</el-dialog>

全局变量:

var notUploadedChunkNumbers_zip = []; // 已经上传过的文件chunkNumber数组
var isUploaded_zip =false;// 文件已经上传成功了
return {

  /** 配置uploader组件的参数,导入zip文件的参数 */
  options: {
    // 可通过 https://github.com/simple-uploader/Uploader/tree/develop/samples/Node.js 示例启动服务
    target: '/api/goods/back/file/fileUpload',
    testChunks: false, // true 会一直返回 40005
    // testChunks: true,   //是否开启服务器分片校验
    // 服务器分片校验函数,秒传及断点续传基础
    checkChunkUploadedByResponse : function (chunk, message) {
        if( isUploaded_zip ){
          console.log("该文件已经上传成功!");
          return true; // return true 会忽略当前文件,不会再发送给后台
        }else{
          try {
            if(notUploadedChunkNumbers_zip.length > 0){ // notUploadedChunkNumbers_zip 未上传的 chunknumber
              return !(notUploadedChunkNumbers_zip.indexOf(chunk.offset + 1) >= 0); // return false会上传当前分片
            }else{
              return false;
            }
          } catch (e) {
            console.log("checkChunkUploadedByResponse error=",e);
          }
        }
    },
    chunkSize:3 * 1024 * 1024,
  },
importZipFile_dialog:false  
}

methods:{

           

/** 导入商品zip文件* */
opendialog_importZipFile(){
  this.importZipFile_dialog = true;//
}
// 上传单个文件
fileAdded(file, event){
  if(/zip/gi.test(file.fileType)){
    // this.panelShow = true;
    this.computeMD5(file);  // 生成MD5
  }else{
    this.$message({ message: "您上传的文件类型不正确,请上传zip文件", type: 'error'});
    return false;
  }
},
// 计算MD5值
computeMD5(file){
  var that = this;
  isUploaded_zip = false; // 这个文件是否已经上传成功过
  notUploadedChunkNumbers_zip = []; // 未成功的chunkNumber
  var fileReader = new FileReader();
  let time = new Date().getTime();
  let md5 = '';

  file.pause();

  fileReader.readAsArrayBuffer(file.file);
  fileReader.onload = function(e){
    if (file.size != e.target.result.byteLength) {
      this.error('Browser reported success but could not read the file until the end.');
      console.log("文件读取失败");
      return false;
    }
    md5 = SparkMD5.ArrayBuffer.hash(e.target.result, false);
    console.log(`MD5计算完毕:${file.id} ${file.name} MD5:${md5} 用时:${new Date().getTime() - time} ms`);
    file.uniqueIdentifier = md5;
    if(md5 != ""){
      checkFileMd5({"md5":md5}).then(res =>{
        if(res.status == 200){
          if(res.data.code == 100){// 上传成功过
            isUploaded_zip = true;
            that.$message({ message: "该文件已经上传成功过了,不能再上传了哦。", type: 'success' });
            file.cancel();
          }else if(res.data.code == 101){ // 该文件没有上传过
            isUploaded_zip = false;
            file.resume();
          }else if(res.data.code == 102){ // 如果102 ,返回未上传过的 chunkNumber 数组
            isUploaded_zip = false;
            notUploadedChunkNumbers_zip = res.data.data;
            file.resume();
          }else{}
        }else{}
      })
    }

    // 添加额外的参数
    // this.uploader.opts.query = {
    //   ...that.params
    // }
  };
  fileReader.onerror = function () {
    this.error('generater md5 时FileReader异步读取文件出错了,FileReader onerror was triggered, maybe the browser aborted due to high memory usage.');
    return false;
  };

},
// 上传进度
onFileProgress(rootFile, file, chunk) {
  console.log(`上传中 ${file.name},chunk:${chunk.startByte / 1024 / 1024} ~ ${chunk.endByte / 1024 / 1024}`)
},
// 上传成功
onFileSuccess(rootFile, file, response, chunk) { // 内部自动调用
  let res = JSON.parse(response);
  this.$message({ message: res.message, type: 'error' });
  if(res.status == 200){ //
    if(isUploaded_zip){ // 不要也可,file.cancel()后就不会onFileSuccess()
      this.$message({ message: "该文件已经上传成功过了,不能再上传了哦。", type: 'success' });
    }else{
      this.$message({ message: "上传成功!", type: 'success' });
      file.cancel();
    }
  }else{
    this.$message({ message: res.message, type: 'error' });
  }
},
onFileError(rootFile, file, response, chunk) {
  this.$message({
    message: response,
    type: 'error'
  })
},

}

参考学习:

转载:https://www.cnblogs.com/xiahj/p/vue-simple-uploader.html#%E5%85%B3%E4%BA%8Evue-simple-uploader

github源码:https://github.com/shady-xia/Blog/tree/master/vue-simple-uploader

猜你喜欢

转载自blog.csdn.net/tangcc110/article/details/85226045