axios进度的请求显示
Posted 勇敢*牛牛
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了axios进度的请求显示相关的知识,希望对你有一定的参考价值。
封装的axios用例;
http.ts
/* eslint-disable */
import axios, AxiosRequestConfig, AxiosError, AxiosResponse from 'axios'
import Qs from 'qs'
import getToken from './token'
import sequenceObject from './common'
import router from '../router'
import store from '../store'
import app from '../main'
const http = axios.create(
timeout: 5000,
data: ,
params: ,
headers:
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
,
transformRequest: [(data: any) =>
if (!data)
data =
return Qs.stringify(data)
],
)
// 声明一个数组用于存储每个ajax 请求标志, 重复请求时取消上一次请求
const pending: [prop: string]: any =
const CancelToken = axios.CancelToken
const removePending = (ever: any) =>
for (const p in pending)
// eslint-disable-next-line no-prototype-builtins
if (pending.hasOwnProperty(p))
// 把参数带上
const url = `$ever.url?$sequenceObject(ever.params)&$sequenceObject(ever.data)`
if (p === `$url&$ever.method`)
pending[p]()
delete pending[p]
// 请求拦截
http.interceptors.request.use((config: AxiosRequestConfig) =>
if (!navigator.onLine && router.currentRoute.path !== '/noNetwork')
router.push(`/noNetwork?redirect=$router.currentRoute.fullPath`)
if (!config.headers['Content-Type'])
config.headers['Content-Type'] = 'application/x-www-form-urlencoded;'
config.data = Qs.stringify(config.data, arrayFormat: 'brackets' )
// config.headers.aaa = 'abc'
// config.headers['token'] = '123'
// config.headers.Authorization = encodeURIComponent(getToken())
// config.headers['Authorization'] = getToken()
config.headers.Authorization = getToken()
// 在ajax 发送前,取消该接口的上一次请求
removePending(config)
config.cancelToken = new CancelToken((cancel: any) =>
// 构造 ajax 请求标志
const url = `$config.url?$sequenceObject(config.params)&$sequenceObject(config.data)`
pending[`$url&$config.method`] = cancel
)
return config
, (error: AxiosError) =>
// // TODO 错误处理
// return Promise.reject(error)
)
// 拦截响应,如果请求错误则重新请求
const retry = 2
const retryDelay = 500
// 返回拦截
http.interceptors.response.use((response: AxiosResponse) =>
// TODO 处理返回结果:错误处理
// 请求成功之后,把请求标志从pending 队列中删除
removePending(response.config)
// 就和后端约定的写法,code值为10000并且你并不是在去请求用户信息的话
if (response.data.code === '10000' && response.config.url?.indexOf('/uaa/user/getUser') === -1)
if ((store.state as any).tokenStatus)
store.commit('clearAll')
router.replace('/newlogin')
const timer = setTimeout(() =>
console.log('登录超时,请重新登录');
clearTimeout(timer)
, 100)
store.commit('updateStatus', false)
return response
, (err) =>
// TODO: 处理返回错误
if (err.message)
console.log('请求失败:', err)
const config = err.config
if (!config || !retry)
return Promise.reject(err)
config.retryCount = config.retryCount || 0
console.log(`第$config.retryCount + 2次请求`)
if (config.retryCount >= retry)
return Promise.reject(err)
config.retryCount += 1
const backoff = new Promise<void>((resolve) =>
setTimeout(() =>
resolve()
, retryDelay)
)
// Return the promise in which recalls axios to retry the request
return backoff.then(() =>
if (!(config.data instanceof FormData))
config.data = Qs.parse(config.data)
return axios(config)
)
)
export default http
api.ts
import Vue from 'vue'
import http from '@/utils/http'
import urls from './url'
// Vue.prototype.host = 'http://192.168.31.116:8080';
// let API_BASE_PATH = `$Vue.prototype.host`
// const mode = process.env.NODE_ENV
// console.log(mode);
// console.log(API_BASE_PATH);
// const API: [prop: string]: string =
// for (const key in urls)
// API[key] = `$API_BASE_PATH$urls[key]`
//
const mode = process.env.NODE_ENV
let API_BASE_PATH
if (mode === 'development')
API_BASE_PATH = 'http://192.168.31.117:8080' // 原版线上环境
// API_BASE_PATH = 'http://192.168.131.104:8080' //131.104
else if (mode === 'test')
// 测试使用的服务器地址
API_BASE_PATH = 'http://192.168.31.117:8080'
else
API_BASE_PATH = 'http://insights.test:8080'
Vue.prototype.host = API_BASE_PATH
const API: [prop: string]: string =
for (const key in urls)
API[key] = `$Vue.prototype.host$urls[key]`
// for (const key in urls)
// API[key] = `$urls[key]`
//
console.log('开发环境',mode);
console.log("服务器地址",Vue.prototype.host);
export default API
// 登录
export const LOGIN = (params: object) =>
return http.post(API.LOGIN, params,
onUploadProgress: (progress) =>
// 格式化成百分数
console.log(progress.loaded,progress.total);
console.log(Math.round(progress.loaded / progress.total * 100) + '%');
)
// 获取切片标注列表
export const GET_ANNOTATION_LIST = (params: object) =>
return http.get(API.ANNOTATION_LIST, params )
// 增加截图
export const ADD_SCREENSHOT = (data: object) =>
return http.post(API.ADD_SCREENSHOT, data,
headers:
'Content-Type': 'multipart/form-data'
,
onUploadProgress: (progress) =>
// 格式化成百分数
console.log(progress.loaded,progress.total);
console.log(Math.round(progress.loaded / progress.total * 100) + '%');
)
// 截图列表
export const GET_SCREENSHOT_LIST = (params: object) =>
return http.get(API.SCREENSHOT_LIST, params )
//测试接口
export const GETT = (params: object) =>
return http.get(API.TEST,params)
参考:
下载文件实现进度条显示
利用axios封装的原生onDownloadProgress属性,该属性为一个回调方法,当axios请求将文件从服务器下载时会进行回调。接收一个回调参数,该回调参数中包含总下载进度,当前下载进度。不多比比直接上代码
<template>
<div>
<button @click="downLoad">下载</button>
<p>
下载进度:downLoadProgress
</p>
</div>
</template>
<script setup>
import ref from '@vue/reactivity';
import axios from 'axios'
var downLoadProgress=ref(0) //定义下载进度
//下载
var downLoad=function()
axios(
url:"http://localhost:3232/api/download",
responseType:'blob',
params:
fileName:'Russ - Psycho (Pt. 2).mp4'
,
// onDownloadProgress 配置该属性代表允许为下载处理进度事件
onDownloadProgress: function (progressEvent) //axios封装的原生获取下载进度的事件,该回调参数progressEvent中包含下载文件的总进度以及当前进度
if (progressEvent.lengthComputable)
//属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
//如果lengthComputable为false,就获取不到progressEvent.total和progressEvent.loaded
downLoadProgress.value = progressEvent.loaded / progressEvent.total * 100 //实时获取最新下载进度
,
).then(res=>
console.log(res)
let link = document.createElement("a");
link.href = URL.createObjectURL(res.data);
link.download = '午夜鸡铃.mp4';
document.body.appendChild(link);
link.click();
URL.revokeObjectURL(link.href);
)
</script>
上传文件实现进度条显示
其实和下载文件进度条显示操作是一样的,axios也同样封装了一个当文件上传至服务器时回调的一个事件。这个事件叫onUploadProgress,与onDownloadProgress一样的配置方法,一样的回调参数。下面直接上代码
<template>
<div>
<input type="file" @change="upload">上传</button>
<p>
上传进度:upProgress
</p>
</div>
</template>
<script setup>
import ref from '@vue/reactivity';
import axios from 'axios'
var upLoadProgress=ref(0) //定义上传进度
//上传
var upload=function(event)
let file = event.target.files[0] //获取选中的文件
const formData = new FormData() //声明一个formdata对象,用于存储file文件以及其他需要传递给服务器的参数
formData.append('userName', 'admin')
formData.append('projectId', '735136fcf95a41248cc94127f7963ea8')
formData.append('file', file)
console.log('formData', formData)
axios(
url:"http://localhost:3232/api/upload",
method: 'post',
headers:
Authorization: 'sdfasfsfwrfrwerrrrrrrrrrrfbdddddddddddddd',
'Content-Type': 'multipart/form-data'
,
data: formdata,
onUploadProgress: function (progressEvent) //原生获取上传进度的事件
if (progressEvent.lengthComputable)
//属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
//如果lengthComputable为false,就获取不到progressEvent.total和progressEvent.loaded
upLoadProgress= progressEvent.loaded / progressEvent.total * 100 //实时获取上传进度
,
).then(res=>
console.log(res)
)
以上是关于axios进度的请求显示的主要内容,如果未能解决你的问题,请参考以下文章