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);
         }
}
meriam bambia
  • 11
  • 1
  • 4

2 Answers2

3

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);
         }
}
Musa
  • 96,336
  • 17
  • 118
  • 137
  • 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. – meriam bambia Apr 26 '19 at 15:13
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);
         }
}
Hiren Siddhpura
  • 189
  • 1
  • 8
  • 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)); ` – meriam bambia Apr 26 '19 at 08:49
  • try again i did change answer – Hiren Siddhpura Apr 26 '19 at 08:57
  • please use : new formdata() and data.append('file', filedata); without it not gone work ! – Hiren Siddhpura Apr 26 '19 at 09:33
  • 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" ? – meriam bambia Apr 26 '19 at 09:45
  • 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 – Hiren Siddhpura Apr 26 '19 at 10:17
  • are you passing in from tag attribute enctype="multipart/form-data" ? – Hiren Siddhpura Apr 26 '19 at 11:15
  • look the refer link : https://stackoverflow.com/questions/17717506/how-to-upload-images-into-mysql-database-using-php-code – Hiren Siddhpura Apr 26 '19 at 11:16
  • Thank you so much for your help. It was just to use `$("#profileImage").prop('files')[0]` in place of `$("#profileImage").val();`. It is clarified above by @Musa. – meriam bambia Apr 26 '19 at 15:16