乘风原创程序

  • Jquery+AJAX实现无刷新上传并重命名文件操作示例【PHP后台接收】
  • 2020/6/23 9:31:38
  • 本文实例讲述了jquery+ajax实现无刷新上传并重命名文件操作。分享给大家供大家参考,具体如下:

    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