meriam bambia
meriam bambia

Reputation: 11

How to save an image file (BLOB) in the database using jquery, ajax and php

I want to save an image in my database as a BLOB file using jquery, Ajax and PHP. I can upload it and display it in the form (if it is inserted manually in the database). However, when I change it on the form, the new image is well displayed but when I click on save it is not saved in the database. I did not find any solution here using jquery, Ajax and PHP, and storing the whole image in the database.

Here is a part of my HTML code (Content/users.php) :

   <img src="images/defaultprofile.png" id="photoUserUpload"
   name="image" onClick="triggerClick()" />
   <input type="file"name="profileImage" id="profileImage" style="display: 
   none;" accept=".jpg, .png" onchange="displayImage(this)" />
</div>
<div> 
  <button id="saveTechItem" class="btn btn-primary saveTechItem">Save</button></div> 

Here is a part of my js code (Data_Scripts/users.js):

$(document).on("click", ".saveItem", function() {
    if (validateForm()) {   
        addOrUpdateItem();
    }
});
function addOrUpdateItem(event) {
    var itemId = $("#userId").val();
    var fullName = $("#txtUserName").val();

    var pic=$("#photoUserUpload").attr('src');
    alert (pic);

    //I tried also to append the file before submit
    var file=new FormData();
    file.append('file', file2);
    //alert (file2);

    var itemData = {
        id: itemId,
        postType: 'addOrUpdate',
        fullName: fullName,
        pic:pic
    };

    $.ajax({
        url: 'data_ajax/users.php',
        data: itemData,
        type: "POST",
        cache: false,
        success: function(data) {
               location.reload();
        },
        error: function(e) {
            alert("error while trying to add or update user!");
        }
    });   
}

Here is a part of my PHP code (DataAjax/user.php):

if (isset($_POST['id'])) {
    $postType = $_POST['postType'];
    if ($postType == "addOrUpdate") {   
        $Id = $_POST['id'];
        $FullName = $_POST['userName']; 
        $pic = base64_encode(file_get_contents($_POST['pic']));
        $data = new Data();
        $db = $data->dataHandler();
        $query = "INSERT INTO Users (`id`, `fullname`, `image`) 
                values ('$Id', '$FullName', '$pic')";
        $db->query($query);
         }
}

Upvotes: 1

Views: 7415

Answers (2)

Musa
Musa

Reputation: 97717

To do a file upload via ajax you have to use a formdata object(where you include the file/blob object), pass it as the data parameter to $.ajax and set processData and contentType to false.

function addOrUpdateItem(event) {
    var itemId = $("#userId").val();
    var fullName = $("#txtUserName").val();
    var pic = $("#profileImage").prop('files')[0];

    var data = new FormData();
    data.append('id', itemId);
    data.append('postType', addOrUpdate);
    data.append('fullName', fullName);
    data.append('pic', pic);

    $.ajax({
        url: 'data_ajax/users.php',
        data: data,
        type: "POST",
        cache: false,
        contentType: false,
        dataType: false,
        success: function(data) {
               location.reload();
        },
        error: function(e) {
            alert("error while trying to add or update user!");
        }
    });   
}

You have to use $_FILES['pic'][tmp_name] to access the file

if (isset($_POST['id'])) {
    $postType = $_POST['postType'];
    if ($postType == "addOrUpdate") {   
        $Id = $_POST['id'];
        $FullName = $_POST['userName']; 
        $pic = base64_encode(file_get_contents($_FILES['pic'][tmp_name]));
        $data = new Data();
        $db = $data->dataHandler();
        $query = "INSERT INTO Users (`id`, `fullname`, `image`) 
                values ('$Id', '$FullName', '$pic')";
        $db->query($query);
         }
}

Upvotes: 4

Hiren Siddhpura
Hiren Siddhpura

Reputation: 189

you passing wrong way image data in postdata try below exmple in your code

html file input:

<input type="file"name="profileImage" id="profileImage" accept=".jpg, .png"  />

script file code with AJAX code:

var itemId = $("#userId").val();
    var fullName = $("#txtUserName").val();
    var filedata = $("#profileImage").val();

    //Your Formdata Ready To Send
    var data = new FormData();
    data.append('file', filedata);
    data.append('id', itemId);
    data.append('fullName', fullName);


$.ajax({
    url: 'data_ajax/users.php',
    data: data,
    type: "POST",
    contentType: false,
    cache: false,
    processData:false,
    success: function(data) {
           location.reload();
    },
    error: function(e) {
        alert("error while trying to add or update user!");
    }
}); 

PHP File Code :

if (isset($_POST['id'])) {
    $postType = $_POST['postType'];
    if ($postType == "addOrUpdate") {   
        $Id = $_POST['id'];
        $FullName = $_POST['fullName']; 

        // chnage this line
        $pic = base64_encode(file_get_contents($_FILES['file']));
        // or you can send all data in serilize way in database like this
        $pic = serialize($_FILES['file']);

        $data = new Data();
        $db = $data->dataHandler();
        $query = "INSERT INTO Users (`id`, `fullname`, `image`) 
                values ('$Id', '$FullName', '$pic')";
        $db->query($query);
         }
}

Upvotes: 0

Related Questions