Telen Stanley Telen Stanley - 2 months ago 20
Ajax Question

How to retrieve image BLOB from formData of jquery ajax in php

I am doing an ajax popup to upload image into filesystem. The image uploading process has the following steps..


  1. choosing the file and crop it to needed size.

  2. the result image is displayed in
    <img>
    tag src as Base64 Code.

  3. converting the Base64 to Blob to send via ajax



Here is the code...

$(document).ready(function(){
$('#btn_save').on('click', function () {
var PaymentStatus = $("#PaymentStatus").val();
var image = $('#image-id').val();

var base64ImageContent = image.replace(/^data:image\/(png|jpg);base64,/, "");
var blob = base64ToBlob(base64ImageContent, 'image/png');
var formData = new FormData();
formData.append('picture', blob);
formData.append('PaymentStatus', PaymentStatus);
$.ajax({
data: formData,
url:"/login/advshop/add",
method: 'GET',
processData: false,
contentType: false,
success: function (result) {
alert("form submitted");
},
error: function (result) {
alert('error');
//alert(result);
}
});
});
});


but I am not able to get the data in my controller..

public function add() {
print_r($_POST['picture']);
}


and the error message is..


Message: Undefined index: picture

Answer

please see my answer..

       $(document).ready(function () {


        $('#btn_save').on('click', function () {
            var image = $('#image-id').val();
            var base64ImageContent = image.replace(/^data:image\/(png|jpg);base64,/, "");
            var PaymentStatus = $("#PaymentStatus").val();
            var formData = new FormData();
            formData.append('image', base64ImageContent);
            formData.append('PaymentStatus', PaymentStatus);



            $.ajax({
                data: formData,
                url: "/login/advshop/add",
                method: 'POST',
                processData: false,
                contentType: false,
                success: function (result) {
                    alert("form submitted");
                },
                error: function (result) {
                    alert('error');
                    //alert(result);

                }
            });
        });
    })

In Controller.

    public function add() {


        $data = base64_decode($_POST['image']);


       file_put_contents('images/test.jpg', $data);
     }

you can directly pass the Base64 image content via ajax using formData append.decode the base64 content and put it in file_put_contents() function.

Comments