vue axios结合elment upload实现上传文件显示进度

vue yekong

axios上传文件的时候,如果文件太大的话,就需要添加一个上传进度了解上传情况,所以我们添加一个进度提示,axios上传进度是通过onUploadProgress来获取的。

html

<el-dialog
  title="上传文件到内部存储或SD卡1"
  :visible.sync="dialogVisible"
  append-to-body
  width="90%">
  <div class="list">
    <el-upload
      class="upload-demo"
      ref="upload"
      :on-change="handlePreview"
      :file-list="fileList"
      :auto-upload="false">
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
    </el-upload>
    <el-progress v-if="progressFlag" :percentage="loadProgress"></el-progress>
  </div>
</el-dialog>

data

  data() {
    return {
      num: 0,
      dialogVisible: false,
      fileList: [],
      loadProgress: 0, // 动态显示进度条
      progressFlag: false // 关闭进度条
    }
  },

js

handlePreview(file, fileList) {
  this.handleImport(file.raw)
},
handleImport(file) {
      var that = this
      const api = '/WebService.asmx/FileAdd'
      let formData = new FormData()
      formData.append('file[0]', file)
      axios({
        method: 'post',
        url: api,
        data: formData,
        onUploadProgress: function (progressEvent) { //原生获取上传进度的事件
          if (progressEvent.lengthComputable) {
            that.progressFlag = true; // 显示进度条
            that.loadProgress = parseInt(progressEvent.loaded / progressEvent.total * 100); // 动态获取文件上传进度
            if (that.loadProgress >= 100) {
              that.loadProgress = 100
              setTimeout(() => {
                that.progressFlag = false
              }, 1000) // 一秒后关闭进度条
            }
          }
        },
      }).then((res) => {
        console.log(res.data)
        if (res.data == '新增媒体文件成功') {
          that.$message({
            message: '新增媒体文件成功',
            type: 'success'
          })
          that.dialogVisible = false
          that.$emit('getdata', 0)
        } else {
          that.$message.error(res.data)
        }
      })
    },
喜欢