微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

带有 Vue 和 Axios 对象的进度条

如何解决带有 Vue 和 Axios 对象的进度条

我想用 Axios 创建一个上传进度条。

服务器发送和响应一切正常。

问题是我不知道如何从导出的对象中获取进度百分比(正确计算)。

我的文件upload.js:

import axios from 'axios'

const baseUrl = 'http://localhost:80/upload.PHP'

const config = {
  Headers: {'Content-Type': 'multipart/form-data'},onUploadProgress: progressEvent => {
    return parseInt(Math.round((progressEvent.loaded / progressEvent.total) * 100))
  }
}

export default {
  send (data) {
    return axios.post(baseUrl,data,config)
  }
}

我的 Vue 组件:

<template>
  <div>
    <label>File:</label>
    <input type="file" id="file" ref="file" @change="changeFile()" />
    <button @click="submit()">Upload</button>
    <br />
    <progress max="100" :value.prop="uploadPercentage"></progress>
  </div>
</template>

<script>
  import upload from '../services/upload.js'
  export default {
    name: 'Upload',data: () => ({
      file: null,uploadPercentage: 0
    }),methods: {
      submit () {
        const formData = new FormData()
        formData.append('file',this.file)
        upload.send(formData)
        .then(res => {
          console.log(res.data)
        })
        .catch(() => {
          console.log('Failure')
        })
      },changeFile () {
        this.file = this.$refs.file.files[0]
      }
    }
  }
</script>

如何从组件submit方法获取onUploadProgress发送的信息以更新数据uploadPercentage? >

谢谢。

问候。

解决方法

您需要将一个函数传递给稍后将调用的发送操作。

见下面的例子

const config = {
  Headers: {'Content-Type': 'multipart/form-data'},onUploadProgress: progressEvent => {
    var progress= parseInt(Math.round((progressEvent.loaded / progressEvent.total) * 100));
    if (config.onProgress)
        config.onProgress(progress);
  }
}

export default {
  send (data,onProgress) {
    config.onProgress= onProgress;
    return axios.post(baseUrl,data,config)
  }
}

然后你上传的代码将是

upload.send(formData,(pogress)=>{
    // Update your uploadPercentage here
})
  .then(res => {
    console.log(res.data)
  })
  .catch(() => {
    console.log('Failure')
  })

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。