Axios封装后 新增上传进度 调用onUploadProgress

在已封装好axios正常使用的页面中  增加onUploadProgress函数  使其在上传时可以实时监听并操作回调

1. 组件逻辑修改

发起请求方式大同小异 正常发送即可  但传参时 除去正常传递的参数  还需要传递一个 uploadChange 参数

const apiPost = ()=>{
  // 发起请求
  const { data } = await uploadFile(fileData, uploadChange)
}



// 上传进度
const uploadChange = (progressEvent) => {
  // 这里需要用Math.ceil对进度进行向上取整 否则可能会出现卡在99%但实际已经上传完成的情况
  const percentCompleted = Math.ceil((progressEvent.loaded * 100) / progressEvent.total)
  console.log(`上传进度: ${percentCompleted}%`)
}

2. API文件逻辑修改

在上传接口中  把刚刚传递来的 uploadChange  作为 onUploadProgress 的值

import request_web from '../utils/request.web'

// 上传图片
export const uploadFile = (data,uploadChange) => {
  return request_web({
    url: '/api/upload',
    method: 'post',
    headers: {
      'content-type': 'multipart/form-data'
    },
    data,
    onUploadProgress: uploadChange
  })
}

至此 调用上传接口时  会随着 axios 的 onUploadProgress 触发而触发 uploadChange   在uploadChange 中操作进度条等逻辑

axios 封装

如果已经封装过  不用看此步骤  前两步就是关键步骤

import axios from 'axios'
import { validateStorage, hasOwnpro, storage } from './util'
import router from '@/router/index'
import { message } from 'ant-design-vue'

// 封装axios构造函数
const request_web = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL + import.meta.env.VITE_API_URL_PREFIX,
  headers: {
    get: {
      'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
    },
    post: {
      'Content-Type': 'application/json;charset=utf-8'
    }
  },
  // 超时时间
  timeout: 10000,
  // 是否跨站点访问控制请求
  withCredentials: false
})

// 请求拦截器
request_web.interceptors.request.use((config) => {
  // 校验本地token
  if (validateStorage('userInfo')) {
    const localUserInfo = JSON.parse(localStorage.getItem('en_userInfo')).value
    if (hasOwnpro(localUserInfo, 'token')) {
      config.headers.Authorization = 'JWT ' + localUserInfo.token
    }
  }
  return config
})

// 响应拦截器
request_web.interceptors.response.use(
  (res) => {
    // axios请求失败
    if (res.status != 200) {
      message.warning('接口请求失败')
      new Error('接口请求失败')
      return
    }

    // 登录超时
    if (res.data.code == 2004) {
      storage.clearStorageSync()
      router.push('/login')
      return
    }

    // 后端接口请求失败
    if (res.data.code && res.data.code != 0) {
      message.warning(res.data.msg)
      return
    }

    // 上传接口特殊回调
    if (res.data.errno == 0) {
      return res
    }

    return res
  },
  (error) => {
    message.warning('服务器异常,请联系管理员')
    return Promise.reject(new Error(error))
  }
)

// 暴露
export default request_web

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值