AJAX请求上传下载进度监控的实现方式

在前端开发中,通过AJAX实现文件上传与下载的进度监控,可以显著提升用户体验。以下是实现进度监控的常用方式:

图片[1]_AJAX请求上传下载进度监控的实现方式_知途无界

一、基于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)实现。
  • 替代方案:使用AxiosonUploadProgress选项。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);});

三、注意事项

  1. 跨域问题
    • 服务器需正确设置CORS头,允许跨域请求,并返回Content-Length头以支持进度计算。
    • 示例:复制代码Access-Control-Allow-Origin: *Content-Length: 123456
  2. 浏览器兼容性
    • XMLHttpRequest的进度事件在主流浏览器中均受支持。
    • Fetch API的进度监控需结合ReadableStream,在部分旧版浏览器中可能不支持。
  3. 性能优化
    • 进度更新频率不宜过高,避免频繁触发UI更新导致性能问题。
    • 可通过requestAnimationFrame或节流(throttling)技术优化进度更新。
  4. 错误处理
    • 需处理网络错误、请求超时等情况,确保用户体验。
    • 示例:javascript复制代码xhr.onerror = function() { console.error('请求失败');};xhr.ontimeout = function() { console.error('请求超时');};

四、总结

  • 上传进度:推荐使用XMLHttpRequest.upload.onprogressAxiosonUploadProgress
  • 下载进度
    • XMLHttpRequest:直接使用onprogress
    • Fetch API:结合ReadableStream实现。
  • 选择方案:根据项目需求和浏览器兼容性选择合适的方式。

通过上述方法,可以高效实现AJAX请求的上传与下载进度监控,提升用户体验。

© 版权声明
THE END
喜欢就点个赞,支持一下吧!
点赞87 分享
People are not just to love and live.
人不是仅仅为了爱而生存的
评论 抢沙发
头像
欢迎您留下评论!
提交
头像

昵称

取消
昵称表情代码图片

    暂无评论内容