ajax 获取上传进度
时间: 2023-10-15 09:08:25 浏览: 48
要获取 AJAX 上传进度,可以使用 XMLHttpRequest 对象中的 onprogress 事件。以下是一个示例代码:
```javascript
function uploadFile() {
var xhr = new XMLHttpRequest();
var fileInput = document.getElementById('fileInput');
var progressBar = document.getElementById('progressBar');
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
var percentComplete = (event.loaded / event.total) * 100;
progressBar.value = percentComplete;
}
};
xhr.open('POST', 'upload.php', true);
xhr.send(fileInput.files[0]);
}
```
在上面的代码中,我们首先获取 XMLHttpRequest 对象和文件输入元素,然后为 XMLHttpRequest 对象的 upload 属性的 onprogress 事件添加一个回调函数。在回调函数中,我们检查事件的 lengthComputable 属性是否为 true,以确保上传进度可计算。如果是,我们计算百分比并将其设置为进度条的值。最后,我们通过调用 XMLHttpRequest 对象的 open 和 send 方法来开始上传文件。
请注意,此代码仅为示例,实际应用中可能需要进行更多的错误处理和用户界面更新。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)