有的项目会使用到附件上传,要求进度条和取消,之前没有使用axios写过,这次刚好碰到了,记录一下;
项目中版本
typescript
"axios": "^0.27.2",
使用
typescript
import axios from 'axios'
handleUploadAjax() {
// 取消令牌生成器
const CancelToken = axios.CancelToken;
// 获取一个令牌对象, 调用source.cancel(),可以取消上传
const source = CancelToken.source();
let formdata = handleUploadFormdata({fileName: '', fileType: '', file: any});
axios({
url: 'url',
headers: {
'Authorization': `Bearer ${getUserToken() || ''}`,
'Content-Type': 'multipart/form-data',
},
method: 'post',
data: formdata,
cancelToken: source.token,
onUploadProgress: (event: any) => { // axios中自带获取文件上传进度条回调
let percent = (event.loaded / event.total * 100).toFixed(2);
}
}).then((res) => {
}).catch((err) => {
});
}
FormData创建
typescript
handleUploadFormdata(params: {fileName: '', fileType:'', file: any}){
const formdata: any = new FormData();
const entries = Object.entries(params);
for (const [key, value] of entries) {
formdata.append(key, value);
};
return formdata;
}