index.html
Ajax上传图片Ajax上传图片
function upload(){
var form = new FormData(document.getElementById("form"));
$.ajax({
url:"upload.php",
type:"post",
data:form,
cache: false,
processData: false,
contentType: false,
success:function(data){
if (data.res == "400") {
$("#upload-result").text("上传成功");
$("#imgdiv").html("");
}else if (data.res == "403") {
$("#upload-result").text("格式不对");
}else if (data.res == "404") {
$("#upload-result").text("上传错误");
}
},
error:function(data){
alert("上传失败")
}
})
}
upload.php
header("Content-type:application/json");
//获取原始文件名
$filename = $_FILES["file"]["name"];
//获取文件后缀名
$hzm = substr($filename,strpos($filename,"."));
//设置新文件名
$newfilename = substr(str_shuffle("QWERTYUIOPASDFGHJKLZXCVBNMqwertyuiopasdfghjklzxcvbnm"),26,10);
// 允许上传的图片后缀
$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\":\"404\"}";
}
else
{
// 此处可以输出文件的详细信息
if (file_exists("upload/" . $newfilename.$hzm))
{
//
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $newfilename.$hzm);
echo "{\"path\":\"$newfilename$hzm\",\"res\":\"400\"}";
}
}
}
else
{
echo "{\"res\":\"403\"}";
}
?>
请在当前目录建立upload文件夹用于存放上传后的图片
GiF Demo
Author
Name:TANKING
Date:2020-04-11
Web:LIKEYUNBA.COM
WeChat:face6009