axios 实现进度监控
在使用 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.log
、alert
或自定义 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);
});
总结
- 使用
onDownloadProgress
和onUploadProgress
可以实现文件的上传和下载进度监控。 - 你可以根据
progressEvent
获取到loaded
和total
字段,计算出上传或下载的进度百分比。 - 可以结合浏览器的
<progress>
元素或自定义进度条来显示上传或下载的进度。 axios
提供了非常简单且直接的方式来实现文件的进度监控,适用于大文件的上传和下载场景。
通过这些方法,你可以轻松地在前端实现文件上传和下载的进度显示。