javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > js axios进度监控

javascript axios 实现进度监控的示例代码

作者:Amo 6729

在使用axios发送HTTP请求时,可以通过onUploadProgress和onDownloadProgress来监控上传和下载的进度,具有一定的参考价值,感兴趣的可以了解一下

在使用 axios 发送 HTTP 请求时,进度监控非常重要,尤其是在上传或下载较大文件时。幸运的是,axios 支持通过 onUploadProgress 和 onDownloadProgress 来监控上传和下载的进度。

1. 监控下载进度

axios 提供了一个 onDownloadProgress 回调函数,可以用来监听下载的进度。该回调会返回一个 progress 对象,包含 loaded(已经下载的字节数)和 total(文件的总字节数)等信息。

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);
});

2. 监控上传进度

对于文件上传,也可以使用 onUploadProgress 来监控上传进度。该回调函数类似,也返回一个 progress 对象,包含上传的字节数和文件的总字节数。

const formData = new FormData();
formData.append('file', fileInput.files[0]); // 假设文件通过 HTML 的文件输入获取

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);
});

3. 结合上传和下载进度

如果你需要同时监控上传和下载进度,可以在同一个 axios 请求中同时使用 onUploadProgress 和 onDownloadProgress

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);
});

4. 显示进度条

结合进度值,你可以使用浏览器的进度条(例如 <progress> 元素)来显示进度。

<progress id="upload-progress" value="0" max="100"></progress>
<progress id="download-progress" value="0" max="100"></progress>
const uploadProgressBar = document.getElementById('upload-progress');
const downloadProgressBar = document.getElementById('download-progress');

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);
    uploadProgressBar.value = percentUploaded;
  },
  onDownloadProgress: (progressEvent) => {
    const percentDownloaded = Math.round((progressEvent.loaded * 100) / progressEvent.total);
    downloadProgressBar.value = percentDownloaded;
  }
})
.then(response => {
  console.log('Upload and download completed!');
})
.catch(error => {
  console.error('Error occurred:', error);
});

5. 自定义进度显示

你还可以自定义进度条的显示方式,例如使用 console.logalert 或自定义 DOM 元素显示进度。

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);
    document.getElementById('upload-status').innerText = `Upload Progress: ${percent}%`;
  },
  onDownloadProgress: (progressEvent) => {
    const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
    document.getElementById('download-status').innerText = `Download Progress: ${percent}%`;
  }
})
.then(response => {
  console.log('Upload and download completed!');
})
.catch(error => {
  console.error('Error occurred:', error);
});

总结

通过这些方法,你可以轻松地在前端实现文件上传和下载的进度显示。

到此这篇关于javascript axios 实现进度监控的示例代码的文章就介绍到这了,更多相关js axios进度监控内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文