vue 通过axios 获取文件上传进度条

对接接口示例方法:

{

toUploadVideo(file) {
  // file为文件信息 
  const that = this
  const token = 'token值'  //若后端不需要token验证,则不需传入
  const url = '请求地址' 
  axios({
    method: 'post',
    url,
    data: file,
    headers: { 'Content-Type': 'multipart/form-data', token },
    onUploadProgress: function(progressEvent) {
      const complete = parseInt((progressEvent.loaded / progressEvent.total * 100 | 0))
      // 这里为上传的进度
      that.progress = complete
    }
  }).then(res => {
  	// 上传成功后续处理
    const { data } = res
    if (data.success) {
      that.$message.success('上传完成!')
    }
  }).catch(err => {
  	// 捕获异常并处理
    console.log(err)
    that.$message.success('上传失败!')
  })
}

}

注意事项

使用axios 需要安装 axios并导入

npm install axios --save 或者 cnpm install axios --save(在终端输入)
import axios from 'axios' (在接口方法文件中引入)

如何实现进度条

在data中定义progress,接口中已对progress进行动态修改
将progress 绑定到进度条上即可
代码如下
{

data() {
   return {
   		progress: 0
	}
}	

}
在这里插入图片描述
css样式
{

.process{
	 height: 7px;
	 color:#ccc;
	 margin: 10px 70px 0;
	 border-radius: 100px;
	 background-color: #CCC;
	 position: relative;
    .process-bar{
       height: 7px;
       background-color: #1890ff;
       border-radius: 100px;
       position: absolute;
       left: 0;
  	}
}

}

文件信息获取

{

getFile (e){
  const $target = e.target || e.srcElement
  const tempFile = $target.files[0]
  const file = new FormData()
  file.append('file', tempFile)  // 上传文件信息
  // 文件限制
  if (tempFile.size > 1024 * 1024 * 10) {
    return this.$message.error('请上传小于10M的视频!')
  } else if (['video/mp4', 'video/ogg', 'video/flv', 'video/avi', 'video/wmv', 'video/rmvb'].indexOf(file.type) === '-1') {
    return this.$message.error('请上传正确的视频格式')
  }
}

}

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐