'POST base64 png in XMLHTTP Request
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
