axios 实现进度监控

[复制链接]
发表于 2025-11-15 04:51:42 | 显示全部楼层 |阅读模式

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

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

×
在使用 axios 发送 HTTP 哀求时,进度监控监控非常紧张,尤其是在上传或下载较大文件时。荣幸的是,axios 支持通过 onUploadProgress 和 onDownloadProgress 来监控监控上传和下载的进度。
1. 监控监控下载进度

axios 提供了一个 onDownloadProgress 回调函数,可以用来监听下载的进度。该回调会返回一个 progress 对象,包罗 loaded(已经下载的字节数)和 total(文件的总字节数)等信息。
 
  1. const axios = require('axios');
  2. axios.get('https://example.com/large-file.zip', {
  3.   onDownloadProgress: (progressEvent) => {
  4.     const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
  5.     console.log(`Download Progress: ${percent}%`);
  6.   }
  7. })
  8. .then(response => {
  9.   console.log('Download completed!');
  10. })
  11. .catch(error => {
  12.   console.error('Error downloading file:', error);
  13. });
复制代码
2. 监控上传进度

对于文件上传,也可以使用 onUploadProgress 来监控上传进度。该回调函数类似,也返回一个 progress 对象,包罗上传的字节数和文件的总字节数。
  1. const formData = new FormData();
  2. formData.append('file', fileInput.files[0]); // 假设文件通过 HTML 的文件输入获取
  3. axios.post('/upload', formData, {
  4.   headers: { 'Content-Type': 'multipart/form-data' },
  5.   onUploadProgress: (progressEvent) => {
  6.     const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
  7.     console.log(`Upload Progress: ${percent}%`);
  8.   }
  9. })
  10. .then(response => {
  11.   console.log('Upload completed!');
  12. })
  13. .catch(error => {
  14.   console.error('Error uploading file:', error);
  15. });
复制代码
3. 连合上传和下载进度

假如你必要同时监控上传和下载进度,可以在同一个 axios 哀求中同时使用 onUploadProgress 和 onDownloadProgress:
  1. const formData = new FormData();
  2. formData.append('file', fileInput.files[0]);
  3. axios.post('/upload', formData, {
  4.   headers: { 'Content-Type': 'multipart/form-data' },
  5.   onUploadProgress: (progressEvent) => {
  6.     const percentUploaded = Math.round((progressEvent.loaded * 100) / progressEvent.total);
  7.     console.log(`Upload Progress: ${percentUploaded}%`);
  8.   },
  9.   onDownloadProgress: (progressEvent) => {
  10.     const percentDownloaded = Math.round((progressEvent.loaded * 100) / progressEvent.total);
  11.     console.log(`Download Progress: ${percentDownloaded}%`);
  12.   }
  13. })
  14. .then(response => {
  15.   console.log('Upload and download completed!');
  16. })
  17. .catch(error => {
  18.   console.error('Error occurred:', error);
  19. });
复制代码
4. 表现进度条

连合进度值,你可以使用欣赏器的进度条(比方 <progress> 元素)来表现进度。
  1. <progress id="upload-progress" value="0" max="100"></progress>
  2. <progress id="download-progress" value="0" max="100"></progress>
复制代码
  1. const uploadProgressBar = document.getElementById('upload-progress');
  2. const downloadProgressBar = document.getElementById('download-progress');
  3. const formData = new FormData();
  4. formData.append('file', fileInput.files[0]);
  5. axios.post('/upload', formData, {
  6.   headers: { 'Content-Type': 'multipart/form-data' },
  7.   onUploadProgress: (progressEvent) => {
  8.     const percentUploaded = Math.round((progressEvent.loaded * 100) / progressEvent.total);
  9.     uploadProgressBar.value = percentUploaded;
  10.   },
  11.   onDownloadProgress: (progressEvent) => {
  12.     const percentDownloaded = Math.round((progressEvent.loaded * 100) / progressEvent.total);
  13.     downloadProgressBar.value = percentDownloaded;
  14.   }
  15. })
  16. .then(response => {
  17.   console.log('Upload and download completed!');
  18. })
  19. .catch(error => {
  20.   console.error('Error occurred:', error);
  21. });
复制代码
5. 自界说进度表现

你还可以自界说进度条的表现方式,比方使用 console.log、alert 或自界说 DOM 元素表现进度。
  1. const formData = new FormData();
  2. formData.append('file', fileInput.files[0]);
  3. axios.post('/upload', formData, {
  4.   headers: { 'Content-Type': 'multipart/form-data' },
  5.   onUploadProgress: (progressEvent) => {
  6.     const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
  7.     document.getElementById('upload-status').innerText = `Upload Progress: ${percent}%`;
  8.   },
  9.   onDownloadProgress: (progressEvent) => {
  10.     const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
  11.     document.getElementById('download-status').innerText = `Download Progress: ${percent}%`;
  12.   }
  13. })
  14. .then(response => {
  15.   console.log('Upload and download completed!');
  16. })
  17. .catch(error => {
  18.   console.error('Error occurred:', error);
  19. });
复制代码
总结


  • 使用 onDownloadProgress 和 onUploadProgress 可以实现文件的上传和下载进度监控。
  • 你可以根据 progressEvent 获取到 loaded 和 total 字段,盘算出上传或下载的进度百分比。
  • 可以连合欣赏器的 <progress> 元素或自界说进度条来表现上传或下载的进度。
  • axios 提供了非常简单且直接的方式来实现文件的进度监控,实用于大文件的上传和下载场景。
通过这些方法,你可以轻松地在前端实现文件上传和下载的进度表现。
回复

使用道具 举报

登录后关闭弹窗

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