element中el-upload上传如何显示进度条且在文件大的时候在进度条没有完成之前取消上传

element中el-upload上传如何显示进度条且在文件大的时候在进度条没有完成之前取消上传

在使用 element UI 的 el-upload 组件上传文件时,可以使用组件的 before-upload 事件和上传进度的 xhr 事件来实现文件上传进度条的显示。在进度条没有完成之前取消上传可以在这个时候通过abort()方法来终止上传。

示例代码如下:

<template>
  <el-upload
    ref="upload"
    :action="url"
    :on-progress="handleProgress"
    :before-upload="handleBeforeUpload"
    :show-file-list="false"
  >
    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
    <el-progress
      :percentage="progress"
      :text-inside="true"
    ></el-progress>
  </el-upload>
</template>

<script>
export default {
  data() {
    return {
      progress: 0,
      xhr:null
    }
  },
  methods: {
    handleBeforeUpload(file) {
      // 文件上传之前进行判断
      if (file.size > maxSize) {
        this.$message.error(`文件大小不能超过 ${maxSize/1024/1024}MB!`);
        return false;
      }
      this.xhr = new XMLHttpRequest()
    },
    handleProgress(event, file, fileList) {
      // 更新进度条进度
      this.progress = Math.round(event.loaded / event.total * 100)
    },
    cancelUpload(){
       // 取消上传
       this.xhr.abort()
    }
  }
}
</script>

上述代码中, handleBeforeUpload 方法在文件上传之前被调用,你可以在这里面进行文件的大小检查,并且将xhr对象设置为全局变量,在 handleProgress 中监听文件上传的进度,通过 event.loaded 和 event.total 来计算百分比。

在文件上传之前,如果文件大小超过限制就返回false,不上传这个文件,并且通过cancelUpload函数来终止上传。

另外, 需要注意的是,在 el-upload组件中需要将show-file-list属性设置为false,表示不显示上传文件的列表。

注意: 上面的例子中的maxSize 是自己定义的

另外,如果有需要在进度条上显示文件上传速度或上传时间等信息可以在handleProgress函数中通过performance.now()函数来计算上传时间或者上传速度等信息

例如:

handleProgress(event, file, fileList) {
      // 计算上传速度
      let speed = (event.loaded - this.previousUploaded) / (performance.now() - this.previousTime)
      this.previousUploaded = event.loaded
      this.previousTime = performance.now()
      this.speed = (speed / 1000).toFixed(2) + 'KB/s'
}

上面的例子中的previousUploaded, previousTime, speed是通过 data 定义的变量,通过它可以计算文件上传的速度.

需要注意的是,在计算上传速度时,必须保证 上传事件(handleProgress)被触发足够频繁,才能保证数据的准确性。