首先:得把php.ini中的post_max_size和upload_max_filesize改成200M或更大(进度条好看效果,默认是2M)
html和js代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
window.onload=function(){
var fm=document.getElementsByTagName('form')[0];
fm.onsubmit=function(evt){//表单事件
var fd=new FormData(fm);//接受表单数据
var xhr=new XMLHttpRequest();
xhr.upload.onprogress=function(evt){//onprogress事件每0.1秒感应一次
//console.log(evt);
var loaded=evt.loaded;//已经上传的附件大小
var total=evt.total;//附件的总大小
var per=Math.floor((loaded/total)*100)+'%';
document.getElementById('son').style.width=per;
document.getElementById('son').innerHTML=per;
}
xhr.onreadystatechange=function(){//ajax返回状态
if (xhr.readyState==4) {
alert(xhr.responseText);
}
}
xhr.open('post','upload.php');//发送ajax方式和路径
xhr.send(fd);//发生表单数据
evt.preventDefault();//阻止浏览器跳转
}
}
</script>
<style>
#pat{
width:400px;
height:5px;
border:1px solid blue;
}
#son{
width:0;
height:100%;
background-color:yellow;
}
</style>
</head>
<body>
<form action="upload.php" >
用户名:<input type="text" name='username'><br>
<input type="file" name='file'><br>
<input type="submit" value='提交'>
<br><br>
<div id='pat'><div id='son'></div></div>
</body>
</html>
php代码:
<?php
if ($_FILES['file']['error']>0) {
exit('上传异常');
}
$path='./upload/';
$name=mt_rand('000','999').$_FILES['file']['name'];//在名字前加上三位随机数,这样能多次上传同一文件
$truename=$path.$name;
$truename=iconv('UTF-8','gb2312',$truename);//转码,使得能够上传中文名称附件
if (move_uploaded_file($_FILES['file']['tmp_name'],$truename)) {//$_FILES['file']['tmp_name']为临时存放目录
echo 'upload success';
}else{
echo 'upload error';
}
?>
效果图: