本文已参与「新人创作礼」活动,一起开启掘金创作之路。
一:监听上传进度,主要利用 onUploadProgress 配置,接受信息,在计算进度,具体代码如下
let formData = new FormData()
formData.append("id", id);
formData.append('file', item.raw)
axios.post('http://192.168.30.244:8001/api/minio/upload',formData,{
onUploadProgress(e){
if(e.lengthComputable){
console.log('上传进度',e.loaded / e.total); //已上传的比例
}
}
}).then(res => {
})
二:axios取消操作 使用了nanoid插件,主要用于生成唯一的id标识; 安装nanoid步骤
安装:
npm i nanoid
导入:
import { nanoid } from "nanoid";
// 发送axios接口
let fileList = this.restfileList
fileList.forEach((item, index) => {
setTimeout(() => {
let notifyKey = 'q' + nanoid() //生成唯一的id
window.sessionStorage.setItem("cancelAxiosId", notifyKey)// 存浏览器session里面,请求拦截器用
this.notifyInit[notifyKey] = this.$notify({
iconClass: "el-icon-loading",
title: '提示',
duration: 0,
offset: 65,
dangerouslyUseHTMLString: true,
message: item.name + '文件上传中...',
onClose: () => {// 取消操作,取消axios接口请求
let cancelArr = window.axiosCancel;
cancelArr = cancelArr || [];
cancelArr.forEach((ele, index) => {
if (ele.id == notifyKey) {
this.$message({
message: '取消上传!',
type: 'warning'
});
ele.cancel("取消请求") // 在失败函数中返回这里自定义的错误信息
delete window.axiosCancel[index]
}
})
}
});
let formData = new FormData()
formData.append("id", id);
formData.append('file', item.raw)
this.$api.systemApi.uploadFile(formData).then((res) => {
if (res.success) {
// 接口成功以后,删除axiosCancel
let cancelArr = window.axiosCancel;
cancelArr = cancelArr || [];
cancelArr.forEach((ele, index) => {
if (ele.id == notifyKey) {
delete window.axiosCancel[index]
}
})
this.$notify({
title: '成功',
message: '文件上传成功!',
type: 'success'
});
this.notifyInit[notifyKey].close()
} else {
// 接口失败删除 window.axiosCancel
let cancelArr = window.axiosCancel;
cancelArr = cancelArr || [];
cancelArr.forEach((ele, index) => {
if (ele.id == notifyKey) {
delete window.axiosCancel[index]
}
})
this.$notify.error({
title: '错误',
message: item.name + "文件上传失败!"
});
setTimeout(() => {
this.notifyInit[notifyKey].close()
}, 100)
}
});
}, 500)
})
// axios 请求拦截器
window.axiosCancel = [] // 全局定义一个存放取消请求的标识
// 请求拦截
axios.interceptors.request.use(config => {
// 在发送请求之前做些什么 验证token之类的
let isLogin = config.url.substring(config.url.length - 5, config.url.length);
if (isLogin != 'login'&& config.url.indexOf("https://geo.datav.aliyun.com/") == -1) {
let token = store.state.user.token;
if(token) {
config.headers['x-auth-token'] = `${token}`;
}
}
if(config.url.indexOf("/minio/upload")!=-1||config.url.indexOf("/api/minio/move")!=-1){
let cancelAxiosId = window.sessionStorage.getItem("cancelAxiosId")
config.cancelToken = new axios.CancelToken(cancel => {
window.axiosCancel.push({
id:cancelAxiosId,
cancel:cancel
})
})
}
NProgress.start();
return config;
}, error => {
// 对请求错误做些什么
return Promise.reject(error);
})