前端实现接口调用进度百分比

引言

在前端开发中,当涉及到文件上传或大型数据传输时,显示接口调用的进度百分比对于提升用户体验至关重要。本文将详细介绍如何在前端实现接口调用进度百分比的显示,并提供示例代码。

1. 使用 XMLHttpRequest 监听上传进度

1.1 HTML 结构

html

深色版本

1<!DOCTYPE html>
2<html lang="en">
3<head>
4    <meta charset="UTF-8">
5    <title>File Upload Progress</title>
6</head>
7<body>
8    <input type="file" id="file-input">
9    <button onclick="uploadFile()">Upload</button>
10    <div id="progress-bar" style="width: 0%; height: 20px; background-color: blue;"></div>
11    <p id="progress-text"></p>
12    <script src="upload.js"></script>
13</body>
14</html>

1.2 JavaScript 代码

javascript

深色版本

1function uploadFile() {
2    const fileInput = document.getElementById('file-input');
3    const file = fileInput.files[0];
4    if (!file) {
5        alert('Please select a file first.');
6        return;
7    }
8
9    const xhr = new XMLHttpRequest();
10    const url = 'https://your-upload-endpoint.com/upload'; // 替换为你的文件上传接口地址
11
12    xhr.open('POST', url, true);
13    xhr.upload.addEventListener('progress', handleProgress, false);
14    xhr.onload = function() {
15        if (xhr.status === 200) {
16            console.log('File uploaded successfully.');
17        } else {
18            console.error('Failed to upload file.');
19        }
20    };
21
22    const formData = new FormData();
23    formData.append('file', file);
24    xhr.send(formData);
25}
26
27function handleProgress(e) {
28    if (e.lengthComputable) {
29        const percentComplete = Math.round((e.loaded / e.total) * 100);
30        updateProgressBar(percentComplete);
31    }
32}
33
34function updateProgressBar(percent) {
35    const progressBar = document.getElementById('progress-bar');
36    const progressText = document.getElementById('progress-text');
37
38    progressBar.style.width = `${percent}%`;
39    progressText.textContent = `${percent}% completed`;
40}

2. 使用 Fetch API 监听上传进度

虽然 Fetch API 默认不支持上传进度事件,但我们可以通过创建 XMLHttpRequest 实例来监听上传进度,并结合 Fetch API 发送请求。

2.1 HTML 结构

html

深色版本

1<!DOCTYPE html>
2<html lang="en">
3<head>
4    <meta charset="UTF-8">
5    <title>File Upload Progress with Fetch</title>
6</head>
7<body>
8    <input type="file" id="file-input-fetch">
9    <button onclick="uploadFileWithFetch()">Upload</button>
10    <div id="progress-bar-fetch" style="width: 0%; height: 20px; background-color: blue;"></div>
11    <p id="progress-text-fetch"></p>
12    <script src="upload-fetch.js"></script>
13</body>
14</html>

2.2 JavaScript 代码

javascript

深色版本

1function uploadFileWithFetch() {
2    const fileInput = document.getElementById('file-input-fetch');
3    const file = fileInput.files[0];
4    if (!file) {
5        alert('Please select a file first.');
6        return;
7    }
8
9    const url = 'https://your-upload-endpoint.com/upload'; // 替换为你的文件上传接口地址
10
11    const formData = new FormData();
12    formData.append('file', file);
13
14    // 创建 Fetch API 请求
15    const request = new Request(url, {
16        method: 'POST',
17        body: formData
18    });
19
20    // 使用 Fetch API 发送请求
21    fetch(request)
22        .then(response => {
23            if (response.ok) {
24                console.log('File uploaded successfully.');
25            } else {
26                console.error('Failed to upload file.');
27            }
28        })
29        .catch(error => console.error('Error:', error));
30
31    // 使用 XMLHttpRequest 监听上传进度
32    const xhr = new XMLHttpRequest();
33    xhr.open('POST', url, true);
34    xhr.upload.addEventListener('progress', handleProgress, false);
35    xhr.send(formData);
36}
37
38function handleProgress(e) {
39    if (e.lengthComputable) {
40        const percentComplete = Math.round((e.loaded / e.total) * 100);
41        updateProgressBar(percentComplete);
42    }
43}
44
45function updateProgressBar(percent) {
46    const progressBar = document.getElementById('progress-bar-fetch');
47    const progressText = document.getElementById('progress-text-fetch');
48
49    progressBar.style.width = `${percent}%`;
50    progressText.textContent = `${percent}% completed`;
51}

3. 注意事项

  • 服务器配置:确保服务器端正确设置了 Content-Length 和 Transfer-Encoding 头部信息,以便客户端可以获取正确的文件大小和上传进度。
  • 浏览器兼容性:虽然大多数现代浏览器支持 XMLHttpRequest 的进度事件,但在使用这些特性时仍需考虑浏览器兼容性问题。
  • 性能优化:在处理大量数据传输时,考虑使用分块上传等策略来优化性能。

4. 总结

通过本文,我们学习了如何使用 XMLHttpRequest 和 Fetch API 在前端实现接口调用进度百分比的显示。这些技术可以帮助提升用户体验,特别是在涉及文件上传或大型数据传输的场景中。如果你在实现过程中遇到任何问题,欢迎随时提问。

  • 4
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值