Ajax 原生ajax-xhr对象文件上传进度条案例
<input type='file' > 浏览文件夹
document.querySelector(‘input’).files; 获得文件对象中的文件集合对象
xhr.onload.progress=function(){}; 上传还在进度时的回调函数
event.lengthComputable; 进度度量衡,100%时返回false,否则返回true;
event.loaded; 已上传文件大小
event.total; 文件总大小
(event.loaded/event.total)*100; 文件上传进度,赋值给进度条的value实现动态改变
前台:
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="jquery-3.4.1.js"></script>
</head>
<body>
<progress min="0" max="100" value="0"></progress>
<input type="file" class='tempFile' multiple >
<button onclick='ajax()'>上传文件</button>
<script>
function ajax()
{
var files=document.querySelector('.tempFile').files;
//get小于1M的数据
var data=new FormData();
for(var i=0;i<files.length;i++)
{
var file=files[i];
data.append("file"+i+":",file);
}
//ajax上传
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function()
{
if(xhr.readyState==4)
{
if(xhr.status==200)
{
console.log(xhr.responseText);
}
}
}
var progress=document.querySelector("progress");
//上传的进度回调
xhr.upload.onprogress=function(event){
//长度度量返回布尔值,100%为false,否则为true
if(event.lengthComputable)
{
//当前进度为上传部分/总长度
progress.value=(event.loaded/event.total)*100;
}
};
//发送
xhr.open('post','3.php',true);
xhr.send(data);
}
</script>
</body>
</html>
后台:
<?php
echo json_encode($_POST);
?>
还没有评论,来说两句吧...