使用ajax和PHP

时间:2016-04-18 12:02:27

标签: php jquery mysql ajax

这是我的问题。我试图上传图像,并借助此URL将图像存储在数据库中相应的文件夹和图像路径中。

http://www.lionblogger.com/how-to-upload-file-to-server-using-php-save-the-path-in-mysql/

当我尝试这种方式时,我会得到正确答案。我用AJAX尝试相同的代码后,工作不正常。我不知道我做了什么错。以下是我的代码。

HTML代码

<div class="input-group form-group">
<label> Upload Your Photo </label>                            
<input type="file" name="upload_photo" id="upload_photo">
</div>
<div class="">
<input type="submit"  class="btn btn-success btn-lg " name="upload_files" id="upload_files" value="UPLOAD" >
</div>

AJAX代码

$("#upload_files").click(function(event){
        event.preventDefault();
        var upload_photo1 = $('#upload_photo').val();
        var photo= upload_photo1.split('\\').pop().split('/').pop();
        var datas="photo="+photo;
    alert(datas);
     if(photo==''){
      sweetAlert({
        title: "WARNING!!!",
        text: "Please Upload All Corresponding Documents And Try Again !!!!",
        type: "warning"
      });
     } else {
    $.ajax({
        type: "POST",
        url: 'php/upload_files.php',
        data:datas
        }).done(function( data ) {
            alert(data);
         });
    }
});

我的PHP文件 Upload_files.php

<?php
    $fileExistsFlag = 0; 
    $fileName = $_POST['photo'];
    var_dump($fileName);
    $link = mysqli_connect("localhost","root","","spark") or die("Error ".mysqli_error($link));

    $query = "SELECT filename FROM filedetails WHERE filename='$fileName'"; 
    $result = $link->query($query) or die("Error : ".mysqli_error($link));
    while($row = mysqli_fetch_array($result)) {
        if($row['filename'] == $fileName) {
            $fileExistsFlag = 1;
        }       
    }

    if($fileExistsFlag == 0)
    { 
        $target = "files/";     
        $fileTarget = $target.$fileName;    
        $tempFileName = $_FILES["fileName"]["tmp_name"];
        $fileDescription = $_POST['Description'];   
        $result = move_uploaded_file($tempFileName,$fileTarget);
        $ext = end(explode('.', $fileName));
        if ($_FILES["fileName"]["size"] > 2097152)
         {
         echo "Sorry, your file is too large.";
         $uploadOk = 0;
         }
      else if($ext != "jpg" && $ext != "png" && $ext != "jpeg"&& $ext != "gif" ) 
      {
         echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
         $uploadOk = 0;
      }
    else
    {
        if($result) { 
            echo "Your file <html><b><i>".$fileName."</i></b></html> has been successfully uploaded";       
            $query = "INSERT INTO filedetails(filepath,filename,description) VALUES ('$fileTarget','$fileName','$fileDescription')";
            $link->query($query) or die("Error : ".mysqli_error($link));            
        }
        else {          
            echo "Sorry !!! There was an error in uploading your file";         
        }
    }   
        mysqli_close($link);
    }

    else {
        echo "File <html><b><i>".$fileName."</i></b></html> already exists in your folder. Please rename the file and try again.";
        mysqli_close($link);
    }   
?>

错误我得到的是enter image description here

请忍受我的怀疑.. PHP的初学者。亲切地帮助我摆脱这个问题。

3 个答案:

答案 0 :(得分:1)

您在js和php中的代码都存在严重问题。您根本没有上传文件。您刚刚上传了文件名。没有描述作为输入,但在您的PHP代码中,您有一个未处理的描述变量。您使用错误的名称处理了该文件。
尝试使用FormData上传文件。首先,使用带有id的表单标记

<form id='myform'>
<div class="input-group form-group">
<label> Upload Your Photo </label>                            
<input type="file" name="upload_photo" id="upload_photo">
</div>
<div class="">
<input type="submit"  class="btn btn-success btn-lg " name="upload_files" id="upload_files" value="UPLOAD" >
</div>
</form>

和js,

    formData = new FormData($("#myForm")[0]);
    formData.append("photo", photo);//your photo name

并在AJAX请求中写下

 data: formData,

并在你的php文件中

<?php
 $fileExistsFlag = 0; 
 $fileDescription ='No idea where this came from';
 $fileName = $_POST['photo'];
 $link = mysqli_connect("localhost","root","","spark") or die("Error ".mysqli_error($link));

 $query = "SELECT filename FROM filedetails WHERE filename='$fileName'"; 
 $result = $link->query($query) or die("Error : ".mysqli_error($link));
 while($row = mysqli_fetch_array($result)) {
     if($row['filename'] == $fileName) {
         $fileExistsFlag = 1;
     }       
 }

 if($fileExistsFlag == 0)
 { 
     $target = "files/";     
     $fileTarget = $target.$fileName;    
     $tempFileName = $_FILES["upload_photo"]["tmp_name"];
     $result = move_uploaded_file($tempFileName,$fileTarget);
     $ext = end(explode('.', $fileName));
     if ($_FILES["upload_photo"]["size"] > 2097152)
      {
      echo "Sorry, your file is too large.";
      $uploadOk = 0;
      }
   else if($ext != "jpg" && $ext != "png" && $ext != "jpeg"&& $ext != "gif" ) 
   {
      echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
      $uploadOk = 0;
   }
 else
{
    if($result) { 
        echo "Your file <html><b><i>".$fileName."</i></b></html> has been successfully uploaded";       
        $query = "INSERT INTO filedetails(filepath,filename,description) VALUES ('$fileTarget','$fileName','$fileDescription')";
        $link->query($query) or die("Error : ".mysqli_error($link));            
    }
    else {          
        echo "Sorry !!! There was an error in uploading your file";         
    }
}   
    mysqli_close($link);
}

else {
    echo "File <html><b><i>".$fileName."</i></b></html> already exists in your folder. Please rename the file and try again.";
    mysqli_close($link);
}   
?>

答案 1 :(得分:0)

问题是您没有传递文件数据 - 只是名称。 在链接的示例中,有一个提交的表单(使用enctype =“multipart / form-data”表示您正在传递二进制数据)。

php代码通过变量$ _FILES [“Filename”] [“tmp_name”]访问文件数据;因为在上传文件时,它存储在临时内部名称(即tmp_name元素)的临时文件夹中。 只需将索引中的“Filename”更改为“fileName”,就不会显示实际的文件数据。

所以一个快速的解决方案是以一个实际形式包装输入字段(使用enctype =“multipart / form-data”),捕获submit事件并在ajax调用中传递整个表单数据 - 所以代替< / p>

data:datas

你通过了

data: new FormData(this)

查看此处的示例: http://www.formget.com/ajax-image-upload-php/

编辑:@khandelwaldeval打败了我的答案; - )

答案 2 :(得分:0)

您的代码看起来很复杂,请尝试使用此

            <form id="picupload">
            <input type="file" accept="image/png, image/jpeg, image/gif" id="upload_photo" name="upload_photo" Required/>
            <button type="submit" name="save" class="btn btn-theme step6"></button>
            </form>

javascript for submission

        <script>
         $("#picupload").submit(function(e) {

                $.ajax({
                  url: "php/upload_files.php", 
                      type: "POST",             
                      data: new FormData(this), 
                      contentType: false,       
                      cache: false,            
                      processData:false,      
                                success: function(data)
                                {
                                 alert(data);
                                 }

                              });
         e.preventDefault(); 
         });

        </script>

使用您的PHP代码处理文件

        <?php
         $fileExistsFlag = 0; 
         $fileDescription ='No idea where this came from';
         $fileName = $_POST['upload_photo'];
         $link = mysqli_connect("localhost","root","","spark") or die("Error ".mysqli_error($link));

         $query = "SELECT filename FROM filedetails WHERE filename='$fileName'"; 
         $result = $link->query($query) or die("Error : ".mysqli_error($link));
         while($row = mysqli_fetch_array($result)) {
             if($row['filename'] == $fileName) {
                 $fileExistsFlag = 1;
             }       
         }

         if($fileExistsFlag == 0)
         { 
             $target = "files/";     
             $fileTarget = $target.$fileName;    
             $tempFileName = $_FILES["upload_photo"]["tmp_name"];
             $result = move_uploaded_file($tempFileName,$fileTarget);
             $ext = end(explode('.', $fileName));
             if ($_FILES["upload_photo"]["size"] > 2097152)
              {
              echo "Sorry, your file is too large.";
              $uploadOk = 0;
              }
           else if($ext != "jpg" && $ext != "png" && $ext != "jpeg"&& $ext != "gif" ) 
           {
              echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
              $uploadOk = 0;
           }
         else
        {
            if($result) { 
                echo "Your file <html><b><i>".$fileName."</i></b></html> has been successfully uploaded";       
                $query = "INSERT INTO filedetails(filepath,filename,description) VALUES ('$fileTarget','$fileName','$fileDescription')";
                $link->query($query) or die("Error : ".mysqli_error($link));            
            }
            else {          
                echo "Sorry !!! There was an error in uploading your file";         
            }
        }   
            mysqli_close($link);
        }

        else {
            echo "File <html><b><i>".$fileName."</i></b></html> already exists in your folder. Please rename the file and try again.";
            mysqli_close($link);
        }   
        ?>