Insert Image into Database without Form Submit AJAX PHP

I’m trying to insert an image from an type=‘file’ HTML tag into an MySQL database using AJAX.

I’m new to using AJAX for image uploads and i think im getting the syntax wrong somewhere.

I’ve done some research on this and i think I’m close.

HTML:

 <input type="file" id="HTMLmyimage"> 

AJAX:

 var $file_data = $('#HTMLmyimage').prop('files')[0];   
    var $form_data = new FormData();                  
    $form_data.append('file', $file_data);



$.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        processData: false, // important
        contentType: false, // important
        url: "PHPURL",
        data: { 
            'BEimage': $form_data,
        },
        success: function(result) {
            alert('User Added')
        },
        error: function(result) {
            alert('error');
        }
    });

PHP:

$image = $request->getParam('BEimage');

$imageData = (file_get_contents($_FILES[$image]['tmp_name']));

$sql4 = "INSERT INTO customerlocation (CustomerID, Username, img) VALUES ('$CustomerID', '$Username', :img)";
     $stmt4 = $db->prepare($sql4);  
     $stmt4->bindParam(':img', $imageData);
     $stmt4->execute();

My current error is saying that $image is not defined but im not sure if im even doing anything before that correct.

Any help on this would be brilliant :slight_smile:

Thank you

i upload images with preview

  1. first i upoad the image to the page
    <input type="file" id="image-input" class="form-control">
    <input type="hidden" name="image" value="" id="image" class="form-control">

     $("#image-input").on("change", function () {            
         files[0] = this.files;
         if (files[0][0].type.match(imageType)) {
             $("#room-image-preview").empty();
             displayFiles(files[0][0], "#room-image-preview");
         }
     });
    
     function displayFiles(file, preview) {
         var imageType = /image.*/;
         if (!file.type.match(imageType)) {
             return true;
         }
         var img = $('<img/>').appendTo(preview);
         var reader = new FileReader();
         reader.onload = (function (aImg) {
             return function (e) {
                 var canvas = document.createElement('canvas');
                 var context = canvas.getContext('2d');
                 context.save();
                 var newImage = new Image();
                 newImage.src = e.target.result;
                 newImage.onload = function () {
    
                     var naturalWidth = newImage.naturalWidth;
                     var naturalHeight = newImage.naturalHeight;
    
                     var width = 0;
                     var height = 0;
    
                     if (naturalWidth > 1280) {
                         width = 1280;
                         height = width * naturalHeight / naturalWidth;
                     } else {
                         width = naturalWidth;
                         height = naturalHeight;
                     }
    
                     canvas.width = width;
                     canvas.height = height;
    
                     context.drawImage(newImage, 0, 0, width, height);
                     var newImg = canvas.toDataURL("image/jpeg");
    
                     aImg.attr('src', newImg);
                     $('#image').val(newImg);
                 };
     
             };
         })(img);
             reader.readAsDataURL(file);
     }
    
  2. next upload a image as string

if (!empty($request->getParam('image'))) {
    $imageResourse = $room->createImageResourse($request->getParam('image'));
    if (!$imageResourse) {
        $this->validator->addError('image', 'Invalid image.');
    }
}

public function createImageResourse($string) {
    $matches = [];
    if (preg_match('~image/([a-z]+);base64~', $string, $matches)) {
        $string = str_replace('data:image/' . $matches[1] . ';base64,', '', $string);
    } else {
        return false;
    }
    $res = imagecreatefromstring(base64_decode($string));
    return $res;
}

using this way i can resize the image before loading or can rotate the image if necessary.