axiox实现请求/响应进度的api,用其实现请求/下载进度条

30 阅读1分钟

axios支持通过onUploadProgressonDownloadProgress来监控上传和下载的进度。以下是具体实现方法:

  1. 监控下载进度:使用onDownloadProgress回调函数,该回调返回一个包含loaded(已下载字节数)和total(文件总字节数)的progressEvent对象2
const axios = require('axios');
axios.get('https://example.com/large-file.zip', {
  onDownloadProgress: (progressEvent) => {
    const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
    console.log(`Download Progress: ${percent}%`);
  }
})
.then(response => {
  console.log('Download completed!');
})
.catch(error => {
  console.error('Error downloading file:', error);
});
  1. 监控上传进度:使用onUploadProgress来监控上传进度,其返回的progressEvent对象与下载进度类似2
const formData = new FormData();
formData.append('file', fileInput.files[0]);
axios.post('/upload', formData, {
  headers: {
    'Content-Type': 'multipart/form-data'
  },
  onUploadProgress: (progressEvent) => {
    const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
    console.log(`Upload Progress: ${percent}%`);
  }
})
.then(response => {
  console.log('Upload completed!');
})
.catch(error => {
  console.error('Error uploading file:', error);
});
  1. 结合上传和下载进度:可以在同一个请求中同时使用onUploadProgressonDownloadProgress来监控上传和下载进度2
const formData = new FormData();
formData.append('file', fileInput.files[0]);
axios.post('/upload', formData, {
  headers: {
    'Content-Type': 'multipart/form-data'
  },
  onUploadProgress: (progressEvent) => {
    const percentUploaded = Math.round((progressEvent.loaded * 100) / progressEvent.total);
    console.log(`Upload Progress: ${percentUploaded}%`);
  },
  onDownloadProgress: (progressEvent) => {
    const percentDownloaded = Math.round((progressEvent.loaded * 100) / progressEvent.total);
    console.log(`Download Progress: ${percentDownloaded}%`);
  }
})
.then(response => {
  console.log('Upload and download completed!');
})
.catch(error => {
  console.error('Error occurred:', error);
});
  1. 结合上传和下载进度注意点我们需要后端配合我们在响应头response中返回一个content-length,这是文件的总字节数或者总块数,我们可以通过两个api获取到当前的上传/下载数和总数对比获得百分比来实现进度条的功能。