1

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);
         }
}

2 Answers 2

4

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);
         }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. It works now. In place of "base64_encode" I used addslashes. There is a little error in your code: data.append not file.append. Thanks for the clarification.
0

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);
         }
}

8 Comments

I don't get an error. The button "save" works, it submits the data to the database, only the image field is empty. I tried exactly your code, it does not work. On the other hand, I tried another solution given that I don't want to use data.append('file', filedata); . So, I kept ` var itemData = { id: itemId, postType: 'addOrUpdate', fullName: fullName, pic:pic };` where pic is var pic = $("#profileImage").val(); and in the PHP code: $d1= $_POST['pic']; $d2=$_FILES [$d1]; $pic = base64_encode(file_get_contents($d2));
try again i did change answer
please use : new formdata() and data.append('file', filedata); without it not gone work !
the value of "filedata" is "C:\fakepath\image_name.png". Should the value of "filedata" be the path of the image? and Why it is "fakepath" ?
try add :[ $pic= base64_encode(file_get_contents($_FILES['file']['tmp_name'])); $data = mysql_real_escape_string($pic); ]may be you get real data of image
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.