在前端开发中,通过AJAX实现文件上传与下载的进度监控,可以显著提升用户体验。以下是实现进度监控的常用方式:
![图片[1]_AJAX请求上传下载进度监控的实现方式_知途无界](https://zhituwujie.com/wp-content/uploads/2025/04/d2b5ca33bd20250409101424.png)
一、基于XMLHttpRequest的进度监控
1. 下载进度监控
- 原理:利用
XMLHttpRequest
对象的progress
事件,监听下载过程中的数据接收情况。 - 代码示例:
const xhr = new XMLHttpRequest();xhr.open('GET', 'https://example.com/file', true);xhr.onprogress = function(event) {if (event.lengthComputable) {const percentComplete = (event.loaded / event.total) * 100;console.log(`下载进度:${percentComplete.toFixed(2)}%`);}};xhr.onload = function() {console.log('下载完成');};xhr.send();const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://example.com/file', true); xhr.onprogress = function(event) { if (event.lengthComputable) { const percentComplete = (event.loaded / event.total) * 100; console.log(`下载进度:${percentComplete.toFixed(2)}%`); } }; xhr.onload = function() { console.log('下载完成'); }; xhr.send();const xhr = new XMLHttpRequest(); xhr.open('GET', 'https://example.com/file', true); xhr.onprogress = function(event) { if (event.lengthComputable) { const percentComplete = (event.loaded / event.total) * 100; console.log(`下载进度:${percentComplete.toFixed(2)}%`); } }; xhr.onload = function() { console.log('下载完成'); }; xhr.send();
2. 上传进度监控
- 原理:通过
XMLHttpRequest.upload
对象的progress
事件,监听上传过程中的数据发送情况。 - 代码示例:
const xhr = new XMLHttpRequest();const formData = new FormData();formData.append('file', document.querySelector('#fileInput').files[0]);xhr.open('POST', 'https://example.com/upload', true);xhr.upload.onprogress = function(event) {if (event.lengthComputable) {const percentComplete = (event.loaded / event.total) * 100;console.log(`上传进度:${percentComplete.toFixed(2)}%`);}};xhr.onload = function() {console.log('上传完成');};xhr.send(formData);const xhr = new XMLHttpRequest(); const formData = new FormData(); formData.append('file', document.querySelector('#fileInput').files[0]); xhr.open('POST', 'https://example.com/upload', true); xhr.upload.onprogress = function(event) { if (event.lengthComputable) { const percentComplete = (event.loaded / event.total) * 100; console.log(`上传进度:${percentComplete.toFixed(2)}%`); } }; xhr.onload = function() { console.log('上传完成'); }; xhr.send(formData);const xhr = new XMLHttpRequest(); const formData = new FormData(); formData.append('file', document.querySelector('#fileInput').files[0]); xhr.open('POST', 'https://example.com/upload', true); xhr.upload.onprogress = function(event) { if (event.lengthComputable) { const percentComplete = (event.loaded / event.total) * 100; console.log(`上传进度:${percentComplete.toFixed(2)}%`); } }; xhr.onload = function() { console.log('上传完成'); }; xhr.send(formData);
二、基于Fetch API的进度监控
1. 下载进度监控
- 原理:
Fetch API
本身不直接支持进度监控,但可以通过ReadableStream
结合Response.body.getReader()
实现。 - 代码示例:
javascript复制代码async function downloadWithProgress(url) { const response = await fetch(url); const reader = response.body.getReader(); const contentLength = +response.headers.get('Content-Length'); let receivedLength = 0; const chunks = []; while (true) { const { done, value } = await reader.read(); if (done) break; chunks.push(value); receivedLength += value.length; console.log(`下载进度:${((receivedLength / contentLength) * 100).toFixed(2)}%`); } const blob = new Blob(chunks); // 可进一步处理,如创建下载链接} downloadWithProgress('https://example.com/file');
2. 上传进度监控
- 原理:
Fetch API
原生不支持上传进度监控,但可以通过结合XMLHttpRequest
或第三方库(如Axios
)实现。 - 替代方案:使用
Axios
的onUploadProgress
选项。javascript复制代码const axios = require('axios');const formData = new FormData();formData.append('file', document.querySelector('#fileInput').files[0]); axios.post('https://example.com/upload', formData, { onUploadProgress: function(progressEvent) { const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total); console.log(`上传进度:${percentCompleted}%`); }}).then(response => { console.log('上传完成');}).catch(error => { console.error('上传失败', error);});
三、注意事项
- 跨域问题:
- 服务器需正确设置
CORS
头,允许跨域请求,并返回Content-Length
头以支持进度计算。 - 示例:
复制代码Access-Control-Allow-Origin: *Content-Length: 123456
- 服务器需正确设置
- 浏览器兼容性:
XMLHttpRequest
的进度事件在主流浏览器中均受支持。Fetch API
的进度监控需结合ReadableStream
,在部分旧版浏览器中可能不支持。
- 性能优化:
- 进度更新频率不宜过高,避免频繁触发UI更新导致性能问题。
- 可通过
requestAnimationFrame
或节流(throttling)技术优化进度更新。
- 错误处理:
- 需处理网络错误、请求超时等情况,确保用户体验。
- 示例:
javascript复制代码xhr.onerror = function() { console.error('请求失败');};xhr.ontimeout = function() { console.error('请求超时');};
四、总结
- 上传进度:推荐使用
XMLHttpRequest.upload.onprogress
或Axios
的onUploadProgress
。 - 下载进度:
XMLHttpRequest
:直接使用onprogress
。Fetch API
:结合ReadableStream
实现。
- 选择方案:根据项目需求和浏览器兼容性选择合适的方式。
通过上述方法,可以高效实现AJAX请求的上传与下载进度监控,提升用户体验。
© 版权声明
文中内容均来源于公开资料,受限于信息的时效性和复杂性,可能存在误差或遗漏。我们已尽力确保内容的准确性,但对于因信息变更或错误导致的任何后果,本站不承担任何责任。如需引用本文内容,请注明出处并尊重原作者的版权。
THE END
暂无评论内容