前端 index.html
[HTML] 纯文本查看 复制代码 <!DOCTYPE html>
<html>
<head>
<script src="jquery-3.4.1.js"></script>
<meta charset="utf-8" />
<title>Ajax提交form</title>
<script type="text/javascript">
function test(){
var form = new FormData(document.getElementById("form"));
$.ajax({
url:"dooo.php",
type:"post",
data:form,
cache: false,
processData: false,
contentType: false,
success:function(data){
//提交成功
var result=document.getElementById("Result");
if (data[0].res == "ok") {
result.innerHTML="<img src=\"upload/"+data[0].path+"\"/>";
}else if (data[0].res == "格式不对") {
result.innerHTML="不允许上传这种格式";
}else if (data[0].res == "文件已存在") {
result.innerHTML="文件已存在";
}else if (data[0].res == "上传错误") {
result.innerHTML="上传错误";
}
},
error:function(data){
var result=document.getElementById("Result");
result.innerHTML="服务器错误";
}
});
}
</script>
</head>
<body>
<h1>AJAX上传文件</h1>
<form id="form" enctype="multipart/form-data">
<input type="file" id="fileAttach" name="file" />
<input type="button" οnclick="test()" value="上传" />
<div id="Result"></div>
</form>
</body>
</html>
服务端 dooo.php
[PHP] 纯文本查看 复制代码 <?php
header("Content-type:application/json");
//获取原始文件名
$filename = $_FILES["file"]["name"];
//获取文件后缀名
$hzm = substr($filename,strpos($filename,"."));
//设置新文件名
$newfilename = MD5($filename);
// 允许上传的图片后缀
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $filename);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "image/gif")
|| ($_FILES["file"]["type"] == "image/jpeg")
|| ($_FILES["file"]["type"] == "image/jpg")
|| ($_FILES["file"]["type"] == "image/pjpeg")
|| ($_FILES["file"]["type"] == "image/x-png")
|| ($_FILES["file"]["type"] == "image/png"))
&& ($_FILES["file"]["size"] < 2048000) // 小于 2000 kb
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "[{\"res\":\"上传错误\"}]";
}
else
{
// 此处可以输出文件的详细信息
if (file_exists("upload/" . $newfilename.$hzm))
{
echo "[{\"res\":\"文件已存在\"}]";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $newfilename.$hzm);
echo "[{\"path\":\"$newfilename$hzm\",\"res\":\"ok\"}]";
}
}
}
else
{
echo "[{\"res\":\"格式不对\"}]";
}
?>
文件目录
记得自己手动建立一个upload的文件夹用于存放上传的文件。 |