当前位置: 移动技术网 > IT编程>脚本编程>vue.js > vue之分片、断点上传

vue之分片、断点上传

2020年07月17日  | 移动技术网IT编程  | 我要评论

哎呀哎呀~~~ 这分片、断点折腾了我四天的时间才搞定。
首先分析一篇文章。https://www.cnblogs.com/xiahj/p/vue-simple-uploader.html。相信大多数搜索的都是他的这篇文章。不过确实算是很详细的了。

vue-simple-uploader其实就是可以拿来用的,但是呢有一部分人不希望用他的样式,一些方法有可能获取不到。先上一下我写的代码吧。我其实也就是做个笔记,方便下次来用

<template>

  <uploader
    ref="uploader"
    :options="options"
    :file-status-text="statusText"
    @file-progress="onFileProgress"
    @file-success="onFileSuccess"
    @file-added="onFileAdded"
    @file-complete="fileComplete"
    @complete="complete"
    class="uploader-example"
  >
    <uploader-unsupport></uploader-unsupport>
    <!-- <uploader-drop> -->
      <uploader-btn :attrs="attrs" >
          <span class="img"></span>
          <span class="title">添加附件</span>
      </uploader-btn>
     
        
    <!-- </uploader-drop> -->
    <uploader-list style="display:none"></uploader-list> //我要隐藏的原因是因为我要获取一些方法,但是呢源码里的一些方法不用这个标签是获取不了的,所以我这么干了一下子哈哈哈
  </uploader>
  
</template>

<script>
 import {ACCEPT_CONFIG} from './cofgi'; //这个文件其实就是上传的格式只不过单独封装了一下
 import SparkMD5 from 'spark-md5';
export default {
    name:"UploaabcddVueSimpleUploader",
    props:{ 
    id:{  //title一定是在父组件绑定的值。父组件绑定什么,子组件接收的这就写什么
       type:String,   // type:是接受过来的类型。一定要是什么类型在子组件里定义
       default: ()=>{
            return null   //没有return会报错,而null 需求而定 也可以空数组等[]
       }
    }
    },
  data () {
    return {
      jindu:0,
      // md5s:"",
      options: {
        target :`url`,
        singleFile:true, //这里是只允许上传一个
        chunkSize: 1024*1024*5,
        testChunks: false, // 是否开启服务器分片校验,
        maxChunkRetries: 20, // 最大自动失败重试上传次数
        query:{
          // name:"1"
        },
        checkChunkUploadedByResponse:(chunk, message)=> {  //这其实跟testChunks类似所以testChunks    false了
          let objMessage = JSON.parse(message);
          return (objMessage.data || []).indexOf(chunk.offset + 1) >= 0
        },  //objMessage.data是后台返回的以上传的片类似[1,3,2]
        headers: {
            //这里设置请求头
        }
      },
      attrs: {
        accept: ACCEPT_CONFIG.getAll() //这里设置上传的格式类型
      },
      statusText: {
        success: '上传成功',
        error: '上传出错了',
        uploading: '正在上传',
        paused: '暂停中',
        waiting: '等待中'
      }
    }
  },
  computed: {
    //Uploader实例
    uploader() {
      return this.$refs.uploader.uploader;
    }
  },
  methods: {
    complete (e) {
      this.$emit('Successfile',1,false)
    },
    fileComplete () {
      console.log('文件上传完成 complete', arguments)
    },
    onFileAdded(file){
      this.$emit('jindu_number',0)
      var objectlist ={}
      objectlist.title =file.name
      objectlist.jindu ="1"  //创建对象是因为要当开始上传的时候要把这一条展示在列表页
      this.$emit('clcicks',objectlist,true)
      this.computeMD5(file);
    },
    onFileSuccess(rootFile, file, message)
    this.jindu=100
    },
    onFileProgress(rootFile, file, chunk) { //一个分片上传成功后,调用该方法
    this.$emit('jindu_number',parseInt(file._prevProgress * 100))  //隐藏情况下保留列表就是为了拿到进度条,如果用它的标签list不会存有顾虑,是用自己的样式,注释掉他封装的标签你去获取进度腻歪屎你
    },
    computeMD5(file) { //计算md5的
     
    let fileReader = new FileReader();
    let time = new Date().getTime();
    let blobSlice = File.prototype.slice || File.prototype.mozSlice || File.prototype.webkitSlice;
    let currentChunk = 0;
    const chunkSize = 10 * 1024 * 1000;
    let chunks = Math.ceil(file.size / chunkSize);
    let spark = new SparkMD5.ArrayBuffer();
    file.pause();
    loadNext();
    fileReader.onload = (e => {
        
        spark.append(e.target.result);
        if (currentChunk < chunks) {
            currentChunk++;
            loadNext();
            // // 实时展示MD5的计算进度
            // this.$nextTick(() => {
            //     // $(`.myStatus_${file.id}`).text('校验MD5 '+ ((currentChunk/chunks)*100).toFixed(0)+'%')
            //     console.log('校验MD5 '+ ((currentChunk/chunks)*100).toFixed(0)+'%')

            // })
        } else {
            let md5 = spark.end();
            this.computeMD5Success(md5, file);

            console.log(`MD5计算完毕:${file.name} \nMD5:${md5} \n分片:${chunks} 大小:${file.size} 用时:${new Date().getTime() - time} ms`);
        }
    });
    fileReader.onerror = function () {
        this.error(`文件${file.name}读取出错,请检查该文件`)
        file.cancel();
    };
    function loadNext() {
        let start = currentChunk * chunkSize;
        let end = ((start + chunkSize) >= file.size) ? file.size : start + chunkSize;
        fileReader.readAsArrayBuffer(blobSlice.call(file.file, start, end));
    }
},
computeMD5Success(md5, file) {
    // 将自定义参数直接加载uploader实例的opts上
    Object.assign(this.uploader.opts, {
        query: {
            ...this.params,
        }
    })
    file.uniqueIdentifier = md5;
    file.resume();
    // this.statusRemove(file.id);
},
  },
  mounted(){
      console.log(this.id)
  }
}
</script>

<style scoped>
.uploader-example .title{position: relative;top: -5px;left: 7px;font-size: 14px;color: #999;}
.uploader-btn:hover{background-color:inherit;}
.uploader-btn:active .img{background: url(../assets/tj_s.png) no-repeat center}
.uploader-example .img{position: relative;left: -2px; border: 0px solid; width: 20px;height: 20px; display: inline-block; background: url(../assets/tj.png) no-repeat center;}
.uploader-drop{height: 50px !important;background-color: #fff;border: 0px solid;}
.uploader-example {
  width: 100%;
  /* padding: 15px; */
  height: 50px;
  /* margin: 40px auto 0; */
  font-size: 12px;
  /* box-shadow: 0 0 10px rgba(0, 0, 0, 0.4); */
}
.uploader-example .uploader-btn {
  margin-right: 4px;
  border: 0px solid;
  position: relative;
  top: 1px;
  height: 55px;
  line-height: 55px;
  left: -5px;
}
.uploader-example .uploader-btn:hover .title{
  color: #666;
}
.uploader-example .uploader-btn:active .title{
  color: #bcbcbc;
}
.uploader-example .uploader-list {
  max-height: 440px;
  overflow: auto;
  overflow-x: hidden;
  overflow-y: auto;
}
</style>
//**************************上传格式如下
export const ACCEPT_CONFIG = {
    image: ['.png', '.jpg', '.jpeg', '.gif', '.bmp'],
    video: ['.mp4', '.rmvb', '.mkv', '.wmv', '.flv'],
    document: ['.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.pdf', '.txt', '.tif', '.tiff',".rar",".zip"],
    getAll(){
        return [...this.image, ...this.video, ...this.document]
    },
};
单独写一个js文件在上面引入即可。兄弟我只能帮你到这里了

本文地址:https://blog.csdn.net/a13145211/article/details/107354247

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网