文件上传el-upload,使用自定义:http-request,不显示默认的进度条

最近在项目中,使用了elementUI的<el-upload>做上传文件,使用自定义:http-request的时候不显示默认的进度条。

其实这个问题有两种解决方案,一种是在action中直接写上要上传路径的url,然后在on-success中获取返回值的路径(保存到服务器中,会返回url的路径地址);另一种方法就是自定义进度条,也就是在:http-request后追加进度条
html:

<el-form-item ref="uploadElement" prop="fileUpdate" label="上传文件">
  <el-upload
  class="upload-demo"
  action="123"
  :http-request="uploadSectionFile"
  :before-remove="beforeRemove"
  :limit="1"
  :on-exceed="handleExceed"
  :file-list="fileList"
  accept=".apk"
>
  <el-button size="small" type="primary">点击上传</el-button>
  <el-progress style="width: 200px;margin-top: 8px" :text-inside="true" :stroke-width="20" :percentage="progressPercent" />
  </el-upload>
</el-form-item>

js:

data() {
  return {
    progressPercent: 0, // 进度条默认为0
  }
}

methods: {
  /**
  * 自定义上传图片的方法
  */
  uploadSectionFile(params) {
    // 上传新文件时,将进度条值置为零
    this.progressPercent = 0

    const file = params.file
    this.ruleForm.packageSize = (file.size / (1024 * 1024)).toFixed(2) + 'M' // 文件大小,转化成M
    this.forms = new FormData() // 实例化一个formData,用来做文件上传
    this.forms.append('file', file)
    // 将图片单独上传,并返回路径
    // 进度条
    const uploadProgressEvent = progressEvent => {
      this.progressPercent = Math.floor((progressEvent.loaded * 100) / progressEvent.total)
    }


    uploadFile(this.forms, uploadProgressEvent).then(res => {
      if (res.code === 200) {
         this.ruleForm.packageUrl = res.data.packageUrl
         this.$refs.uploadElement.clearValidate() // 如果上传文件成功,就把必填校验动态移除
      }
    }).catch(response => {
       console.log('文件上传失败')
    })
  },
}


最重要的是这个
const uploadProgressEvent = progressEvent => {
this.progressPercent = Math.floor((progressEvent.loaded * 100) / progressEvent.total)
}

然后在接口中,将参数传过去
export function uploadFile(obj, onUploadProgress) {
return request({
url: '上传的路径',
method: 'POST',
data: obj,
headers: {
'Content-Type': 'multipart/form-data'
},
onUploadProgress
})
}

posted on 2020-10-19 14:32  吃的快不吐骨头  阅读(4188)  评论(0编辑  收藏  举报