Vue中实现分块上传

基于vue-simple-uploader

安装

 npm install vue-simple-uploader --save

注入插件

import uploader from 'vue-simple-uploader'
Vue.use(uploader)

封装

<template>
  <div class="home">
    <uploader :options="options" :file-status-text="statusText" :autoStart="autoStart" class="uploader-example"
      ref="uploader" style="width: 100%;" @file-success="fileSuccess">
      <uploader-unsupport></uploader-unsupport>
      <uploader-drop>
        <uploader-btn :directory="directory" class="uploader-btn">上传</uploader-btn>
      </uploader-drop>
      <uploader-list></uploader-list>
    </uploader>
  </div>
</template>

<script>
import { getToken } from '@/libs/util'

export default {
  name: 'upload',
  props: {
    uploadUrl: {
      type: String,
      default: ''
    },
    singel: {
      type: Boolean,
      default: false
    },
    chunkSize: {
      type: Number,
      default: 1024 * 1024 * 3 // 块大小 单位b 1024*1024*3
    },
    directory: {
      type: Boolean, // 是否选择文件夹
      default: false
    },
    autoStart: {
      type: Boolean, // 选择文件后自动开始上传
      default: true
    },
    uploadQuery: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      options: {
        target: this.uploadUrl, // 上传地址
        testChunks: false, // 是否开启服务器分片校验
        chunkSize: this.chunkSize,
        singleFile: this.singel, // 单文件上传
        headers: { // 额外的一些请求头
          Authorization: `Bearer ${getToken()}`
        },
        query: { // 其他额外的参数
          hashid: this.uploadQuery
        }
      },
      statusText: {
        success: '上传成功',
        error: '上传失败',
        uploading: '上传中',
        paused: '暂停中',
        waiting: '等待中'
      }
    }
  },

  watch: {
    uploadQuery (newVal, oldVal) {
      this.options.query.hashid = newVal
    }
  },
  methods: {
    /**
     * @param {*} chunk 块信息
     * @param {*} message  返回的消息
     * @description 文件上传成功后触发,返回消息
     */
    fileSuccess (rootFile, file, message, chunk) {
      let temp = JSON.parse(message).result[0]
      this.$emit('upload-success', {
        size: temp.size,
        url: temp.url
      })
    },
    /**
     * @description 文件夹上传成功后触发,返回消息
     */
    fileComplete (rootFile) {

    },
   

  }

}
</script>
<style  scoped>
.uploader-example {
  padding: 15px;
  font-size: 12px;
}
.uploader-btn {
  color: #fff;
  background-color: #2d8cf0;
  border-color: #2d8cf0;
  border-radius: 4px;
}
</style>

效果:
文件
Vue中实现分块上传_第1张图片
文件夹
Vue中实现分块上传_第2张图片
其他的一些重要的参数
https://github.com/simple-uploader/Uploader/blob/develop/README_zh-CN.md

你可能感兴趣的:(Vue.js)