使用axios上传文件时需要进度条,可通过监听axios的onUploadProgress获取当前文件上传进度,进度条可以用antd的Progress
实现过程中出现问题request.upload.addEventListener in not a function。
参考南柯一梦的博客https://www.cnblogs.com/leeke98/p/10491358.html
原来和mockjs有关,把项目中mockjs的引用去掉,问题迎刃而解
const [uploading, setUploading] = useState(false);
const [percent, setPercent] = useState(null);
const upload = async () => {
const config = {
onUploadProgress: (progressEvent) => {
const percentNum = Math.round((progressEvent.loaded * 100) / progressEvent.total);
console.log(percentNum);
setPercent(percentNum);
},
withCredentials: true,
};
let url = 'api/xxx';
const formData = new window.FormData();
formData.append("file",file); //上传的数据
try {
setUploading(true);
const { err, status } = await axios.post(url, formData, config);
} catch (e) {
console.log('ignore', e);
}
setUploading(false);
}