版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/CodingNoob/article/details/83537091
<!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">
<title>Document</title>
<style>
*{margin:0;padding:0;}
.progress {
width: 300px;
height: 20px;
border: 1px solid hotpink;
border-radius: 20px;
overflow: hidden;
}
.step {
height: 100%;
width: 0;
background: greenyellow;
}
</style>
</head>
<body>
<div class='progress'>
<div class="step"></div>
</div>
<input type="file" name='icon' id="file">
<input type="button" value='ajax2.0'>
</body>
<script>
// 如果我们要使用 ajax2.0 结合FormData 来提交数据 必须使用 post
document.querySelector('input[type=button]').onclick = function () {
//1.创建对象
var xhr = new XMLHttpRequest();
//2.设置请求行(get请求数据写在url后面)
xhr.open('post', './test.php');
//3.设置请求头(get请求可以省略,post不发送数据也可以省略)
// 如果使用的时 formData可以不写 请求头 写了 无法正常上传文件
// xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//3.5注册回调函数
xhr.onload = function () {
console.log(xhr.responseText);
}
// XHR2.0新增 上传进度监控
xhr.upload.onprogress = function (event) {
// console.log(event);
var percent = event.loaded / event.total * 100 + '%';
console.log(percent);
// 设置 进度条内部step的 宽度
document.querySelector('.step').style.width = percent;
}
// XHR2.0新增
var form = document.createElement('form');
form.appendChild(document.querySelector('#file'));
var data = new FormData(form);
data.append('name', 'zhangsan'); // 添加其他参数
data.append('age', 19); // 添加其他参数
//4.请求主体发送(get请求为空,或者写null,post请求数据写在这里,如果没有数据,直接为空或者写null)
xhr.send(data);
}
</script>
</html>
<?php
// 获取提交的文件信息
print_r($_FILES);
// 保存上传的数据
move_uploaded_file($_FILES['icon']['tmp_name'],'./files/'.$_FILES['icon']['name']);
?>