I have this HTML code:
<div id="container">
<div id="calendar">
</div>
</div>
<button class="btn btn-dark mb-1" onclick="captureAndSave()">Format</button>
And this JS code:
<script>
function captureAndSave()
{
// Select "calendar" element
var elementToCapture = document.querySelector('section.content');
// Hide ".noPrint" elements
var elementsToHide = elementToCapture.querySelectorAll('.noPrint');
elementsToHide.forEach(function(element)
{
element.style.visibility = 'hidden';
});
html2canvas(elementToCapture).then(function(canvas)
{
var imageBase64 = canvas.toDataURL('image/png');
elementsToHide.forEach(function(element)
{
element.style.visibility = 'visible';
});
var link = document.createElement('a');
link.href = imageBase64;
link.download = 'captura.png';
link.click();
});
}
</script>
Pressing the button is supposed to download an image of the content "section.content", right? Well, this action is actually carried out, but when trying to adapt this code and make it download the image to a server folder instead of being downloaded to the user's computer, I can't do it.
I tried this approach:
<script>
function captureAndSave()
{
var elementToCapture = document.querySelector('section.content');
var elementsToHide = elementToCapture.querySelectorAll('.noPrint');
elementsToHide.forEach(function (element) {
element.style.visibility = 'hidden';
});
html2canvas(elementToCapture).then(function (canvas) {
var imageBase64 = canvas.toDataURL('image/png');
elementsToHide.forEach(function (element) {
element.style.visibility = 'visible';
});
var xhr = new XMLHttpRequest();
xhr.open('POST', 'assets/imagen.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
var data = 'image=' + encodeURIComponent(imageBase64);
xhr.send(data);
xhr.onload = function () {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
if (response.success) {
alert(response.message);
} else {
alert('Error: ' + response.message);
}
}
};
});
}
</script>
PHP code called "image.php" that I tried to manage saving to the server without success:
<?php
$response = array();
if(isset($_POST['image']))
{
$imageData = $_POST['image'];
$filePath = '../vistas/img/temp/imagen.png';
if(file_put_contents($filePath, base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $imageData))))
{
$response['success'] = true;
$response['message'] = 'The image has been saved successfully.';
}
else
{
$response['success'] = false;
$response['message'] = 'There was an error saving the image.';
}
}
else
{
$response['success'] = false;
$response['message'] = 'No image received.';
}
header('Content-type: application/json');
echo json_encode($response);
?>
Any suggestions on what I could change or a better approach to what I want to achieve? First of all, Thanks.