10

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Ajax上传图片</title>
    <meta charset="utf-8">
    <script src="https://www.jq22.com/jquery/jquery-3.3.1.js"></script>
</head>
<body>
    <h1>Ajax上传图片</h1>
    <!-- 表单 -->
    <form id="form" enctype="multipart/form-data">
        <input type="file" id="fileAttach" name="file"/>
        <input type="button" onclick="upload()" value="上传"/>
    </form>

    <!-- 显示结果 -->
    <h2 id="upload-result"></h2>

    <!-- 显示图片 -->
    <div id="imgdiv"></div>

    <!-- Ajax上传 -->
    <script>
        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("<img src=\"upload/"+data.path+"\"/>");
                    }else if (data.res == "403") {
                        $("#upload-result").text("格式不对");
                    }else if (data.res == "404") {
                        $("#upload-result").text("上传错误");
                    }
                    
                },
                error:function(data){
                    alert("上传失败")
                }
            })
        }
    </script>
</body>
</html>

upload.php

<?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

GIF 2020-4-11 22-40-22.gif

Author

Name:TANKING
Date:2020-04-11
Web:LIKEYUNBA.COM
WeChat:face6009


TANKING
4.8k 声望495 粉丝

热爱分享,热爱创作,热爱研究。