axios上传文件带进度条
原生写法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>上传文件进度条</title>
<style>
body {
position: relative;
width: 1920px;
height: 984px;
}
.box {
position: absolute;
left: 50%;
top: 30%;
transform: translate(-50%, -30%);
}
.wrap {
width: 300px;
height: 20px;
box-shadow: 0 0 10px pink inset;
border-radius: 10px;
border: 2px solid #eee;
background: rgba(0, 0, 0, 0.5);
margin-top: 20px;
position: relative;
display: none;
}
.children {
width: 0;
height: 20px;
box-shadow: 0 0 5px #eee outset;
border-radius: 10px;
background: -webkit-linear-gradient(left, #FF34B3 0%, #FF7256 50%, yellow 100%);
}
#percent {
position: absolute;
top: 0px;
left: 0;
margin: 0;
}
</style>
</head>
<body>
<div class="box">
<input type="file" id='input'>
<div class="wrap" id='wrap'>
<div class="children" id='children'>
<!-- <input type="file" accept="image/*" multiple> -->
</div>
<p id='percent'>0</p>
</div>
</div>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
var Input = document.getElementById('input')
var Wrap = document.getElementById('wrap')
var Children = document.getElementById('children')
var Percent = document.getElementById('percent')
Input.onchange = function (event) {
console.log('event', event)
let file = event.target.files[0]
const formData = new FormData()
formData.append('userName', 'admin')
formData.append('projectId', '735136fcf95a41248cc94127f7963ea8')
formData.append('file', file)
console.log('formData', formData)
var percent = 0;
uploadPhoto(formData, function (e) {
Wrap.style.display = 'block'
percent = e.loaded / e.total * 100
Children.style.width = percent + '%'
Percent.innerHTML = Math.ceil(percent) + '%'
Percent.style.left = Math.ceil(percent) + '%'
}, function (res) {
if (res.code === 1) {
alert('上传成功')
Children.style.width = 0 + '%'
Wrap.style.display = 'none'
}
})
}
function uploadPhoto(payload, callback1, callback2) {
axios({
url: 'http://192.168.31.253:8080/upload',
method: 'post',
headers: {
Authorization: 'sdfasfsfwrfrwerrrrrrrrrrrfbdddddddddddddd',
'Content-Type': 'multipart/form-data'
},
onUploadProgress: function (progressEvent) { //原生获取上传进度的事件
if (progressEvent.lengthComputable) {
//属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
//如果lengthComputable为false,就获取不到progressEvent.total和progressEvent.loaded
callback1(progressEvent);
}
},
data: payload
}).then(res => {
callback2(res.data);
}).then(error => {
console.log(error)
})
}
</script>
</body>
</html>
// 内容转载自 [小九的小酒](https://www.jianshu.com/p/2ec9cc044096/)
在框架中封装后的写法
/**
* @description 创建请求实例
*/
function createService() {
// 创建一个 axios 实例
const service = axios.create()
// 请求拦截
service.interceptors.request.use(requestInterceptor, requestRejectInterceptor)
// 响应拦截
service.interceptors.response.use(responseSuccessHandler, responseErrorHandler)
return service
}
function stringify(data) {
return qs.stringify(data, { allowDots: true, encode: false })
}
/**
* @description 创建请求方法
* @param {Object} service axios 实例
*/
function createRequest(service) {
return function(config) {
// const token = util.cookies.get('token')
const configDefault = {
headers: {
// Authorization: token,
'Content-Type': 'application/x-www-form-urlencoded'
},
timeout: 99999999999,
baseURL: process.env.VUE_APP_API,
data: {}
}
const option = merge(configDefault, config)
// 下面这个是重点
if (config.callback) {
option['onUploadProgress'] = (progressEvent) => {
//原生获取上传进度的事件
if (progressEvent.lengthComputable) {
//属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
//如果lengthComputable为false,就获取不到progressEvent.total和progressEvent.loaded
config.callback(progressEvent)
}
}
}
// 处理 get 请求的参数
// 请根据实际需要修改
if (!isEmpty(option.params)) {
option.url = option.url + '?' + stringify(option.params)
option.params = {}
}
// 当需要以 form 形式发送时 处理发送的数据
// 请根据实际需要修改
if (
!isEmpty(option.data) &&
option.headers['Content-Type'] === 'application/x-www-form-urlencoded'
) {
if (util.cookies.get('uid')) {
option.data = Object.assign(option.data, {
uid: util.cookies.get('uid'),
access_token: util.cookies.get('access_token'),
partner_id: util.cookies.get('partner_id')
})
}
// option.data = stringify(option.data)
}
return service(option)
}
}
// 用于真实网络请求的实例和请求方法
export const service = createService()
export const request = createRequest(service)
// 通用接口
export function CommonFunEmpty(method, url, data, callback = '') {
// 接口请求
return request({
url,
method,
data,
callback
});
}
// 接口调用
(async() => {
let data = await context.root.CommonFunEmpty('POST', params.url, params.data, fun_upload_percent)
})()
const fun_upload_percent = e => {
const percent = e.loaded / e.total * 100
}
标签:function,axios,const,option,进度条,上传,percent,progressEvent,data
From: https://www.cnblogs.com/DTCLOUD/p/17119287.html