原生ajax上传文件+进度条

时间:2022-08-29 09:50:59
<!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>上传文件</title>
<style>
#big
{
width
:300px;
height
:30px;
background-color
:rgb(224, 229, 233);
border
:solid 1px #ccc;
}
#small
{
width
:0px;
height
:28px;
background-color
:rgb(211, 25, 25);
border
:solid 1px #ccc;
}
</style>
<script>
function t(){
var xhr= new XMLHttpRequest();
xhr.upload.onprogress
=function(evt){
//这里的evt表示onprogress
//console.log(evt);
var baifenbi=Math.round((evt.loaded/evt.total)*100)+'%';
document.getElementById('small').style.width=baifenbi;
}
xhr.open(
'post','index.php',true);
xhr.onreadystatechange
=function(){
if(xhr.readyState==4){
//console.log(xhr.responseText);
}
}
//xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// var submit=document.getElementById('submit').value;
// var upload=document.getElementById('upload').value;
// xhr.send('submit='+submit+'&upload='+upload);

var fm=document.getElementsByTagName('form')[0];
var data=new FormData(fm);
xhr.send(data);
}
</script>
</head>
<body>
<form action="" >
<!-- <input type="file" id="upload" name="upload"></input> -->
<input type="file" name="upload">
<input type="button" value="上传" onclick="t()"></input>
</form>
<div id="big">
<div id="small"></div>
</div>

</body>
</html>

 

<?php
header('content-type:text/html;charset=utf-8');
//第一步:判断是否是http post上传的
// if(!is_uploaded_file($_FILES['upload']['tmp_name'])){
// exit('非法上传');
// }

//第二步:判断是否有错误

if($_FILES['upload']['error']!=0){
exit('上传文件错误');
}
//第三步:判断文件类型
$fs = finfo_open(FILEINFO_MIME_TYPE); //得到一个mime类型资源
$mime= finfo_file($fs,$_FILES['upload']['tmp_name']); //上文文件得mime类型
$arr= array('image/jpeg','image/png','image/gif'); //允许上传的mime类型
if(!in_array($mime,$arr)){
exit('上传类型不符');
}
//第四步:获取文件拓展名
$index=strrpos($_FILES['upload']['name'],'.'); //获取文件最后一个点的位置
$ext=substr($_FILES['upload']['name'],$index); //取出扩展名
//第五步:判断文件大小,允许,上传小于2M的文件

if($_FILES['upload']['size']>2*1024*1024){
exit('文件上传过大');
}
//第六步:临时文件
$filename=$_FILES['upload']['tmp_name'];
//第七步:构建目标文件
$path='./upload';
@
mkdir($path);
$destionation=$path.'/'.uniqid().$ext;
//第八部:正式上传
if(move_uploaded_file($filename,$destionation)){
echo "上传成功";
}
else{
echo "上传失败";
}

原生ajax上传文件+进度条

原生ajax上传文件+进度条