0

Here is my problem. I tried to upload image and I store images in corresponding folder and image path in database with the help of this URL.

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

When i tried that way i will get correct answer. After i tried same code with AJAX is not working properly. I dont know what mistake I did. Below is my code.

HTML code

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

$("#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);
         });
    }
});

And my PHP file 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);
    }   
?>

Error what im getting is enter image description here

Please Bear my doubts.. Beginner of PHP.Kindly Help me out of this problem.

Deval Khandelwal
  • 3,187
  • 1
  • 24
  • 37
Kavya Shree
  • 882
  • 1
  • 12
  • 45
  • Possible duplicate of [jquery ajax File Upload php](http://stackoverflow.com/questions/23980733/jquery-ajax-file-upload-php) – Shadow Apr 18 '16 at 12:23
  • You only send the name of the file (if any) in your ajax request, not the contents of the file. See linked topic for a sample code for file uploading. – Shadow Apr 18 '16 at 12:25

3 Answers3

1

You have serious issues with your code in both js and php. You have not uploaded the file at all. You have just uploaded the file name. There is no description as input but in your php code you have a description variable unhandled. You have handled the file with the wrong name.
Try uploading the file with FormData. First, use the form tag with an 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>

and in the js,

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

and in the AJAX request, write

 data: formData,

and in your php file

<?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);
}   
?>
Deval Khandelwal
  • 3,187
  • 1
  • 24
  • 37
0

The problem is that you are not passing the file data - just the name. In the example from your link there is a form that is beeing submitted (with enctype="multipart/form-data" which means you are passing binary data).

The php code accesses the file data through the variable $_FILES["Filename"]["tmp_name"]; because when uploading a file it is stored in a temp folder with a temporary internal name (that's the tmp_name element). By simply changing 'Filename' to 'fileName' in the index does not give you your actual file data.

So a quick solution is to wrap the input field in an acutal form (with the enctype="multipart/form-data"), catch the submit event and pass the whole form data in the ajax call - so instead of

data:datas

you pass

data: new FormData(this)

check out the example here: http://www.formget.com/ajax-image-upload-php/

EDIT: @khandelwaldeval beat me to the answer ;-)

mikesp
  • 159
  • 6
0

Your code looks complicated try using this

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

use your php code for processing the file

        <?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);
        }   
        ?>
Hardik Patil
  • 67
  • 1
  • 8