POST base64 png in XMLHTTP Request

Issue

For some reason this information is impossible to find a straight forward answer for, I have been trying to solve this for over a week. So please give a useful answer to it only!

I am saving canvas.toDataUrl image into the server with the following steps:

JAVASCRIPT

function captureCanvas(){
    html2canvas(displayScreen).then(canvas =>{
        postPicture(canvas.toDataURL());
    })
}

function postPicture(data){
    let xhr = new XMLHttpRequest();
    xhr.onload = function (){
        if (this.status == 200){
         let result = document.getElementById('result-pic');   
         console.log('this is the response:'+this.response);
         result.src = this.response;
        }
    }
    xhr.open('POST', 'storeImage.php', true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send('image='+data);
}

Then trying to store it with server side / display the result back into html file:
PHP

$baseFromJavascript = $_POST['image'];
$data = base64_decode(preg_replace('#^data:image/w+;base64,#i', '', $baseFromJavascript));
$filepath = "./upload/image.png";
file_put_contents($filepath,$data);

echo $baseFromJavascript;

Neither it’s being opened as an image locally or being displayed into html, even though the html img has the base64 data.

Solution

You have to do some changes in Javscript as well as in PHP

Encode your data in JS so that request sent proper

function captureCanvas(){
    html2canvas(displayScreen).then(canvas =>{
        postPicture(canvas.toDataURL());
    })
}

function postPicture(data){
    let xhr = new XMLHttpRequest();
    xhr.onload = function (){
        if (this.status == 200){
         let result = document.getElementById('result-pic');   
         console.log('this is the response:'+this.response);
         result.src = this.response;
        }
    }
    xhr.open('POST', 'storeImage.php', true);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send('image='+encodeURIComponent(data));
}

Change your php script as below:

$baseFromJavascript = $_POST['image'];
$data = $baseFromJavascript;
list($type, $data) = explode(';', $data);
list(, $data)      = explode(',', $data);
$data = base64_decode($data);
$filepath = "./upload/image.png";
file_put_contents($filepath,$data);

echo $baseFromJavascript;

Answered By – B. Desai

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published