javascript用ajax的FormData上传图片,并检查后缀是否为图片jpg格式,并图片重新命名,包括php文件
<html>
<head>
<meta http-equiv="content-type" content="text/html charset=utf-8"/>
<title></title>
</head>
<body>
<form id="form" method="post" action="">
<input type="file" name="myfile"/>
<input type="submit" value="上传" id="upload"/>
</form>
<script>
var btn=document.getElementById('upload');
btn.onclick=function(){
var form=document.getElementById('form');
var fd=new FormData(form);
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if(xhr.readyState===XMLHttpRequest.DONE){
if(xhr.status<200||xhr.status>=300&&xhr.status!==304){
alert('服务器异常,上传失败');
}
var data=xhr.responseText; //返回php输出的值,比如上传成功或是失败或是格式错误
if(data==""){
//检查值是否存在,是否为空
alert('服务器保存文件失败');
}
alert(data); //弹出php返回的值,比如成功或是失败等情况
}
};
//这三句一定要写在xhr.onreadystatechange语句后面
xhr.open('post','uploadss.php');
xhr.send(fd);
return false; //阻止自动提交
};
</script>
</body>
</html>
下面是php文件,php接收到上传的图片,做出判断,看格式是否错误
<?php
//这里的myfile就是上面input里面name="myfile"
if(isset($_FILES['myfile'])&&$_FILES['myfile']['error']===UPLOAD_ERR_OK){
$pic=$_FILES['myfile']['name'];
$pic=strstr($pic,"."); //strstr是检查后缀以点开始到结束的字符
$path="./upfile\\";
if($pic!==".jpg"){
echo "上传格式错误,请重新上传";
}else if($_FILES['myfile']['tmp_name']){
$name=time().".jpg"; //以时间戳来保存图片名字
move_uploaded_file($_FILES['myfile']['tmp_name'],$path.$name);
echo "上传成功!";
}else{
echo "文件上传失败";
}
}
?>