0

I have an image in my mysql DB, in type longblob. I have an ajax call that requests the image and on success, changes my html image src to be the received image. My ajax post response is the image name (114046.png) but it will trigger the ajax error section, not success. Can someone look through my code and tell me where im going wrong?

Saving image in DB

    public function UploadImage($imageData) {
        global $dbCon;

        $imgFile = $imageData['file']['name'];
        $imgSize = $imageData['file']['size'];

        if(empty($imgFile)){
            error_log("image file empty");
        }

        $imgExt = strtolower(pathinfo($imgFile,PATHINFO_EXTENSION)); // get image extension

        // valid image extensions
        $valid_extensions = array('jpeg', 'jpg', 'png', 'gif'); // valid extensions

        if(!in_array($imgExt, $valid_extensions)) { 
            error_log("Sorry, only JPG, JPEG, PNG & GIF files are allowed."); 
        }  

        // Check file size '5MB'
        if($imgSize > 5000000) {
            error_log("Sorry, your file is too large.");
        }

        // rename uploading image
        $userpic = rand(1000,1000000).".".$imgExt;

        $sql = 'UPDATE userinfo SET image=(:image) WHERE username="'.$this->currentUsername.'"';

        $stmt = $dbCon->prepare($sql);

        $stmt->bindParam(':image', $userpic);
        $stmt->execute();

        if($stmt == false) { 
            error_log("Failed to put image info in DB");
        } else {
            //image uploaded
        }
    }

Getting the image from the DB

    public function GetImage() {
        global $dbCon;

        $stmt = $dbCon->query("SELECT image FROM userinfo WHERE username='".$this->currentUsername."'");

        $fetchResult = $stmt->fetch();
        $data = $fetchResult["image"];

        if($stmt == false) { 
            error_log("Failed to put image info in DB");
        } else {
            $this->LatestUpdate = "Get Image";
            $this->image = $data;
        }
    }

    public function GetTheImage() {
        return $this->image;
    }

Responding to ajax

        if($this->model->LatestUpdate() == "Get Image") {
            header("Content-type: image/png");
            echo $this->model->GetTheImage();
            exit();
        }

Ajax call (Set the HTML image to the received image)

window.onload = SetImage;

function SetImage() {
    data = "action=" + "getImage";
    $.ajax({
            url: '../index.php', // point to server-side PHP script 
            dataType: 'image/png',  // what to expect back from the PHP script, if anything
            data: data,                         
            type: 'post',
            success: function(image) {
                console.log("success");
                $("#profileImage").attr("src", image);
            }, error: function(xhr, status, error) {
                alert("Error" + xhr.responseText);
            }
     });
}
Oblivion
  • 585
  • 2
  • 8
  • 26
  • What is the response you get from the server after the ajax? – Accountant م Dec 03 '17 at 15:12
  • @Accountantم My ajax post response is the image name (114046.png), the code will alert "Error114046.png" – Oblivion Dec 03 '17 at 15:17
  • Do you get something in `status` or `error` parameters ? – Accountant م Dec 03 '17 at 15:23
  • Also note that you are returning the image file name not the image data itself, so remove the `header("Content-type: image/png");` – Accountant م Dec 03 '17 at 15:25
  • @Accountantم "Error No conversion from text to image/png" with error parameter, but i want the image data so i can display it right? – Oblivion Dec 03 '17 at 15:28
  • Sure you have to return the image itself not it's name to use it in the HTML. But the code you post is saving just the image name. What exactly your problem is ? do you want to save and retrieve the image data ? or you just want to retrieve it's name in the ajax success function not the error function ? – Accountant م Dec 03 '17 at 15:37
  • @Accountantم Save image data and retrieve it from server to display – Oblivion Dec 03 '17 at 15:42
  • Your ajax should get only the image **name/url** and set it in the `src` attribute as you did in your code . So remove `dataType: 'image/png',` from the javascript and remove `header("Content-type: image/png");` from the PHP And let the browser request the image in the `src` from the server after you update the `src`. – Accountant م Dec 03 '17 at 15:51
  • @Accountantم generally, should the image be stored in the DB or should the location of the image on the server be stored in the DB? If so, i have no need to store the image as a longblob, i should just store the image on the server and the path to it in a regular DB column? – Oblivion Dec 03 '17 at 16:09
  • Unless you have a good reason, saving the images in the filesystem is better than the database see this [question](https://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay). If they are public images then save them in a public folder and let the Apache serve them instead of you. – Accountant م Dec 03 '17 at 16:09
  • In my work I never save images in the databases because that increases the backup cost. Instead save them in folders and just save the path in the database. – Accountant م Dec 03 '17 at 16:11
  • @Accountantم but then how do i avoid the issue of the browser not being able to load from my file system (im using xampp) Not allowed to load local resource: file:///C:/xampp/htdocs/Web%20Assignment%20Code/Model/profileImages/class.png – Oblivion Dec 03 '17 at 18:10
  • Convert the filesystem path to a web path before you send it to the browser as you want. For example `str_replace($_SERVER['DOCUMENT_ROOT'], "", $serverAbsulotePath);` – Accountant م Dec 03 '17 at 18:31

0 Answers0