在已封装好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