0

I am currently doing a website and I have some problem uploading an image into an image folder in Cpanel. I managed to save the image name into my database but not the file of the image. What can I do to upload the file of an image into my images folder?

I managed to show the detail of all my console.log in chrome.

<!DOCTYPE html>

<html>
<head>
   <link rel="stylesheet" href="styles.css">
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
   <script src="//code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
  <div class="nav">
    <div class="span10 offset1">
      <form action="#" method="post" name="form_name" id="createform" class="form_class" >
        <div class="control-group">
          <label class="control-label">Facilities Image</label>
          <div class="controls">
             <img id="imgNewUser" height="100">
             <input type="file" name="SelectImg" id="SelectImg" value="My Picture" accept="image/*" onchange="onpreviewFile()">
          </div>
        </div>
        <div class="form-actions">
          <button type="button" class="btn btn-success" id="upload-button" onclick="createfacilities()">Update</button>
        </div>
      </form>
    </div>
      <script>
        function onpreviewFile() {
            var preview = document.querySelector('img'); //selects the query named img
            var file    = document.querySelector('input[type=file]').files[0]; //sames as here
            var reader  = new FileReader();
          
            reader.onloadend = function () {
                preview.src = reader.result;
            }
        
            if (file) {
                reader.readAsDataURL(file); //reads the data as a URL
                uploadFile(); // testing
            } else {
                preview.src = "";
            }
        }
      
        onpreviewFile();
      
        function uploadFile() {
            var file= $('#SelectImg')[0].files;
            console.log("file"+ file);
          
            var formData = new FormData();
            formData.append("fileToUpload", file);
            console.log($('#SelectImg')[0].files[0]);
          
            $('#SelectImg').attr("src", serverURL() + "/images/" + file + "_s");
            console.log("did _s");
          
            var fd = new FormData(document.getElementById("SelectImg"));
            fd.append("label", "WEBUPLOAD");
            console.log("now ajax");
            var url = serverURL + "/upload.php";
          
            $.ajax({
                url: url,
                type: "POST",
                data: fd,
                processData: false,  // tell jQuery not to process the data
                contentType: false   // tell jQuery not to set contentType
            }).done(function( data ) {
                console.log("PHP Output:");
                console.log( data );
            });
        }
      
        function createfacilities() {
            var image = document.getElementById("SelectImg").files[0].name;
            document.getElementById("createform").submit(); //form submission
            alert("facilities_ID : " + facilities_ID 
                + " \n image : " + image
                + "\n\n Form Submitted Successfully.");
          
            var image = document.getElementById("SelectImg").files[0].name;
            var url = serverURL()+ "/addfacilities.php";
            var JSONObject = {
                "facilities_Img" : image
            };
          
            $.ajax({
                url: url,
                type: 'GET',
                data: JSONObject,
                dataType: 'json',
                contentType: "application/json; charset=utf-8",
                success: function (arr) {
                    _addDescriptionResult(arr);
                },
                error: function () {
                    alert("not okay");
                }
            });
        }
      
        function _addDescriptionResult(arr) {
            document.getElementById("facilities_ID").innerHTML = localStorage.getItem("facilities_ID");
            if (arr[0].result === 1) {
                alert("okay");
            } else {
                alert("not okay 1");
            }
        }
      </script>
    </div>
  </body>
</html>

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
header("Content-Type: application/json; charset=UTF-8");

include("global.php");

try{
 $filename = tempnam('images', '');
 $new_image_name = basename(preg_replace('"\.tmp$"', '.jpg', $filename));
 unlink($filename);
 
 //print_r($_FILES);
 move_uploaded_file($_FILES["file"]["tmp_name"], "images/" . $new_image_name); 
 
 make_thumb("images/" .$new_image_name, "images/" .$new_image_name . "_s", 100);
 
 $json_out = "[" . json_encode(array("result"=>$new_image_name)) . "]";
 echo $json_out;
}
catch(Exception $e) {
 $json_out =  "[".json_encode(array("result"=>0))."]";
 echo $json_out;
}
?>
Adeline
  • 15
  • 5

1 Answers1

0

There were a few things wrong with your code. I've removed the extraneous code and documented the changes.

One of the main issues was you were calling serverURL in several places without it being defined anywhere. I removed those calls and am simply calling upload.php. You can change this as needed.

I also changed the upload dir to the same directory as the PHP file to keep things simple. You can change as needed.

Most of the code was taken from here: jQuery AJAX file upload PHP

index.html

<html>
<head>
      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <script src="//code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
  <div class="nav">
    <div class="span10 offset1">
      <form action="#" method="post" name="form_name" id="createform" class="form_class" enctype="multipart/form-data">
        <div class="control-group">
          <label class="control-label">Facilities Image</label>
          <div class="controls">
             <img id="imgNewUser" height="100">
             <input type="file" name="SelectImg" id="SelectImg" value="My Picture" onchange="onpreviewFile()">
          </div>
        </div>
        <div class="form-actions">
          <button type="button" class="btn btn-success" id="upload-button" onclick="uploadFile()">Update</button>
        </div>
      </form>
    </div>
      <script>
        function onpreviewFile() {
            var preview = document.querySelector('img'); 
            var file    = document.querySelector('input[type=file]').files[0]; 
            var reader  = new FileReader();

            reader.onloadend = function () {
                preview.src = reader.result;
            }

            if (file) {
                reader.readAsDataURL(file);
                uploadFile(); // don't think you should attempt upload here
            } else {
                preview.src = "";
            }
        }

        function uploadFile() {
            var file_data = $('#SelectImg').prop('files')[0];   
            var form_data = new FormData();                  
            form_data.append('file', file_data); // The name here ('file') needs to match what PHP is expecting
            alert(form_data);
            $.ajax({
                url: 'upload.php', // point to server-side PHP script 
                dataType: 'text',  // what to expect back from the PHP script, if anything
                cache: false,
                contentType: false,
                processData: false,
                data: form_data,
                type: 'post',
                success: function(php_script_response){
                    alert(php_script_response); // display response from the PHP script, if any
                }
             });
        }
      </script>
    </div>
  </body>
</html>

Upload.php

<?php
try{
    if (0 < $_FILES['file']['error']) {
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    } else {

        $filename = tempnam('images', '');
        $new_image_name = basename(preg_replace('"\.tmp$"', '.jpg', $filename));
        unlink($filename);

        move_uploaded_file($_FILES['file']['tmp_name'], $new_image_name);

        echo "[" . json_encode(array("result"=>$new_image_name)) . "]";
    }
}
catch(Exception $e) {
    $json_out =  "[".json_encode(array("result"=>0))."]";
    echo $json_out;
}
waterloomatt
  • 3,662
  • 1
  • 19
  • 25