<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="./form.css">
<title>Document</title>
<style>
.progress{
width: 800px;
height: 30px;
border:1px solid green;
margin:0 auto;
overflow:hidden;
position: relative;
}
.in{
width: 3%;
height: 100%;
background: red;
}
span{
position: absolute;
left:390px;
top:0;
}
</style>
</head>
<body>
<form id="form1">
用户名:<input type="text" name="username" >
密码:<input type="password" name="password" >
头像:<input type="file" name="myfile" id="pic">
<input type="button" value="发送ajax请求" id="sub">
</form>
<div class="progress" >
<div class="in"></div>
<span>0%</span>
</div>
<img src="" alt="">
<script>
document.querySelector("#sub").onclick = function(){
var xhr = new XMLHttpRequest();
xhr.open("post","03-uploadFile.php");
// 我想自己来设置一个请求头,看行不行--注意了,如果人为了设置了请求头,那么文件数据无法正确的传递
// xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
// 获取表单数据 new FormData 这种方式不需要设置头部
var myform = document.querySelector("#form1");
var formData = new FormData(myform);
//必须写在send之前 监听上传的进度 onprogress 上传的过程中会一直触发的 事件函数 如果文件大会很多次
xhr.upload.onprogress=function(e){
// e就有当前文件上传的过程中的一些数据
// console.log(e);
// e.loaded 当前上传了多大 e.total 总共有多大
var num=Math.floor((e.loaded/e.total)*100);
var percent=num+"%";//12.22
console.log(percent)
document.querySelector(".in").style.width=percent;
document.querySelector(".progress span").innerHTML=percent;
}
xhr.send(formData);
xhr.onreadystatechange = function(){
if(xhr.status == 200 && xhr.readyState == 4){
console.log(xhr.responseText);
}
}
}
</script>
</body>
</html>
用farmdata上传文件,视频,音频等显示进度
猜你喜欢
转载自blog.csdn.net/YangL666/article/details/82389170
今日推荐
周排行