当前位置: 首页 > article >正文

前端结合 react axios 获取真实下载、上传进度

首页确保项目中使用了axios

axios ondownloadprogress中total总为零,content-length不返回?

点我查看 Axios Documention

 npm i axios
 yarn add axios

以下我们举例接口调用配置说明:

由于接口下载时,不确定文件下载时长,所以直接设置不限时

 timeout: -1,

由于 axios 已提供下载上传回掉函数(callback),所以我们直接调用就好

import { useState } from "react"

type ProgressStatusType = "normal" | "active" | "success" | "exception"

interface TestReportState {
  showProgressModal: boolean
  downloadPercent: number
  downloadStatus: ProgressStatusType
}

const [showProgressModal,setShowProgressModal] = useState<boolean>(false)
const [downloadPercent,setDownloadPercent] = useState<number>(0)
const [downloadStatus,setDownloadStatus] = useState<ProgressStatusType>("normal")

// 外层调用
const downloadFile = async (filename: string): Promise<void> => {
  try {
	setShowProgressModal(true)
    setDownloadStatus("active")
    const res = await downLoadFileTemp({ filename }, state)
    setDownloadStatus("success")
    downloadFileAction(filename, res)
  } catch (error) {
    setDownloadStatus("exception")
    console.error("downloadFile->", error)
  }
}

export const downLoadFile = (params: { filename: string }, setDownloadPercent:()=>void ): Promise<Blob> => {
  return get(`api/getFile?${qs.stringify(params)}`, {
    timeout: -1, // 不限时
    onDownloadProgress: (progressEvent: ProgressEvent) => {
		setDownloadPercent(calcProgress(progressEvent)) 
    },
    onUploadProgress:  (progressEvent: ProgressEvent) => {
    // Do whatever you want with the Axios progress event
    
  },
  })
}

为了提高代码互用性与可维护性所以将计算进度的逻辑做了封装

/**
 * 计算进度条百分比
 */
export const calcProgress = (progressEvent: ProgressEvent): number => {
  const { loaded = 0, total = 0 } = progressEvent || {}
  return Math.ceil((loaded / total) * 100) || 0
}

你可能有疑惑 progressEvent 中所含有的字段,请看以下示例:


/**
 * Events measuring progress of an underlying process, like an HTTP request (for an XMLHttpRequest, or the loading of the underlying resource of an <img>, <audio>, <video>, <style> or <link>).
 *
 * [MDN Reference](https://developer.mozilla.org/docs/Web/API/ProgressEvent)
 */
interface ProgressEvent<T extends EventTarget = EventTarget> extends Event {
    /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ProgressEvent/lengthComputable) */
    readonly lengthComputable: boolean;
    /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ProgressEvent/loaded) */
    readonly loaded: number;
    readonly target: T | null;
    /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/ProgressEvent/total) */
    readonly total: number;
}

axios ondownloadprogress中total总为零,content-length不返回?

  1. 后端在header中加上content-length
  2. 如果使用了Gzip做了文件分块获取到的 content-length 也可能是不准确的,所以可以让后端将此信息新建一个字段解决 例如:
response header {
	...
	custom-content-length: 2040
}

http://www.kler.cn/news/273348.html

相关文章:

  • NFS性能优化参考 —— 筑梦之路
  • Unity中实现游戏对象逐渐放大的脚本教程
  • FreeRTOS入门基础
  • 【数据结构和算法初阶(C语言)】二叉树的顺序结构--堆的实现/堆排序/topk问题详解---二叉树学习日记②
  • GEE:为什么在机器学习分类或回归时,提取特征变量后的样本点下载到本地时,数据为空且缺少坐标?
  • AR/MR产品设计(二):如何用一双手完成与虚拟对象的自然交互
  • 【QCM4490】开机慢
  • C++_day6
  • Qt5.14.2 深入理解Qt多线程编程,掌握线程池架构实现高效并发
  • 【低照度图像增强系列(3)】EnlightenGAN算法详解与代码实现
  • 房产销售平台|基于Spring cloud+ Mysql+Java+ Tomcat的房产销售平台设计与实现(可运行源码+数据库+设计文档)
  • ONLYOFFICE文档8.0全新发布:私有部署、卓越安全的协同办公解决方案
  • 数字创新的引擎:探索Web3的前沿科技和商业模式
  • Hystrix的原理及应用:构建微服务容错体系的利器(一)
  • GitLab/Github从头开始配置秘钥
  • Java 学习和实践笔记(40):String类详解
  • 外包干了3个月,技术明显进步。。。。。
  • 学习Java十一天总结
  • 聚类分析 | Matlab实现基于PCA+DBO+K-means的数据聚类可视化
  • 钉钉小程序 - - - - - 如何通过一个链接打开小程序内的指定页面
  • 【OpenCV C++】找到图像中最亮的区域中心,求该区域ROI的平均亮度
  • 电话机器人语音识别用哪家更好精准度更高。
  • HUAWEI Pocket 2外屏实时查看App动态,小小窗口大便捷
  • Spring项目问题:登录中用户名或密码为空问题
  • CentOS7 操作firewall防火墙
  • 对IO流原理及、分类及IO模型的一个大概认识【Java基础题】
  • 算法第三十天-矩阵中移动的最大次数
  • Android 性能优化——APP启动优化
  • 供应链投毒预警 | 开源供应链投毒202402月报发布啦
  • UnityShader(十七)透明效果