axios获取接口进度(上传文件)

[复制链接]
发表于 2026-1-28 23:40:05 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

×
封装的post哀求,onUploadProgress为获取进度,signal为停止哀求的参数
  1.   post(path: string, body?: IObject, headers?: IObject, timeout: number = 30000, signal?: any, onUploadProgress?: (progressEvent: any) => void): Promise<IHttpResponse> {
  2.     return http({
  3.       url: path,
  4.       method: "post",
  5.       timeout: timeout,
  6.       headers: {
  7.         "Content-Type": "application/json;charset=UTF-8",
  8.         appType: app.appType,
  9.         ...headers
  10.       },
  11.       data: body,
  12.       onUploadProgress: onUploadProgress,
  13.       signal: signal
  14.     });
  15.   }
  16. }
复制代码
界说接口
  1. export const uploadMaterial = (formData: any, signal?: AbortSignal, onProgress?: (percent: number) => void) => {
  2.   return baseService.post(
  3.     "/api/training/material/upload",
  4.     formData,
  5.     {},
  6.     3600000,
  7.     signal,
  8.     (progressEvent) => { // 直接传递 onUploadProgress 回调函数
  9.       if (progressEvent.lengthComputable && onProgress) {
  10.         const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total);
  11.         onProgress(percentCompleted); // 调用传入的回调,并传递进度百分比
  12.       }
  13.     }
  14.   );
  15. };
复制代码
调用接口
这里的使用场景是批量上传,
  1. async function uploadFilesSequentially() {
  2.   let allFilesSucceeded = true;
  3.   if (file.value.length > 0) {
  4.     for (let i = 0; i < file.value.length; i++) {
  5.       if (file.value[i]) {
  6.         let formData = new FormData();
  7.         formData.append("file", file.value[i]);
  8.         formData.append("categoryId", categoryId.value);
  9.         fileList.value[i].status = "uploading"; // 更新当前文件上传状态
  10.         try {
  11.           const handleProgress = (percent) => {
  12.             if (percent >= 90) {
  13.               if (timer.value) return; // 如果已经有定时器在运行,则直接返回
  14.               // 设置定时器,每秒更新一次进度
  15.               timer.value = window.setInterval(() => {
  16.                 fileList.value[i].progress += 1;
  17.                 if (fileList.value[i].progress > 98) {
  18.                   timer.value && window.clearInterval(timer.value);
  19.                 }
  20.               }, 1000);
  21.             } else {
  22.               // 在进度达到80之前,直接按照传入的 percent 更新进度
  23.               fileList.value[i].progress = percent; // 这里应该是更新 progress.value,而不是 complete
  24.             }
  25.           };
  26.           const res = await uploadMaterial(formData, abortController.value.signal, handleProgress); // 等待上一次上传完成
  27.           if (res.code == 0) {
  28.             console.log("文件 " + (i + 1) + " 上传成功"); // 打印当前文件上传成功的消息
  29.             fileList.value[i].status = "success"; // 更新当前文件上传状态
  30.             file.value[i] = null; // 更新当前文件上传状态
  31.             fileNumber.value++;
  32.           } else {
  33.             allFilesSucceeded = false; // 如果有文件上传失败,更新标志
  34.             fileList.value[i].status = "error"; // 更新当前文件上传状态
  35.             file.value[i] = null; // 更新当前文件上传状态
  36.             console.error("文件 " + (i + 1) + " 上传失败");
  37.             fileNumber.value++;
  38.           }
  39.         } catch (error) {
  40.           allFilesSucceeded = false; // 如果捕获到异常,也更新标志
  41.           // ElMessage.success("所有文件上传完成");
  42.         }
  43.       }
  44.     }
  45.     if (allFilesSucceeded && fileList.value.length > 0) {
  46.       console.log("所有文件上传成功"); // 所有文件上传成功后打印的消息
  47.       closeDialog();
  48.       // 这里可以调用其他函数,如 handleClose(); 或 emit("refreshDataList");
  49.     } else {
  50.       console.log("部分文件上传失败"); // 如果有文件上传失败,则打印此消息
  51.       abortController.value.abort();
  52.       fileList.value = [];
  53.       categoryId.value = "";
  54.       file.value = [];
  55.       multipleUpload.value.clearFiles();
  56.       abortController.value = new AbortController();
  57.     }
  58.     // ElMessage.success("所有文件上传完成");
  59.   }
  60. }```
  61. 中止请求
  62.   // 初始化取消控制器实例
  63. const abortController = ref(new AbortController());
  64. 在取消请求的方法中
  65. const interruptRequest = ()=>{
  66. // 取消文件上传
  67.   abortController.value.abort();
  68.     // 创建新的取消控制器实例
  69.     abortController.value = new AbortController();
  70. }
复制代码
代码只是简单的示例,直接使用大概有未知bug

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!qidao123.com:ToB企服之家,中国第一个企服评测及软件市场,开放入驻,技术点评得现金
回复

使用道具 举报

登录后关闭弹窗

登录参与点评抽奖  加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表