1๐
โ
First, you convert the image to base64 format and base64 URL store
into a tag: For example, I am using a chart.js line chart
<canvas id="myChart"></canvas>
<a type="button" id="link2" class="btn btn-primary">Download</a>
<script type="text/javascript">
$(document).ready(function(){
var ctx = document.getElementById('myChart').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [{
label: "My First dataset",
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45],
}]
},
// Configuration options go here
options: {
bezierCurve : false,
animation: {
onComplete: done
}
}
});
//This function is used to store the image in data-src in a tag
function done(){
var url = chart.toBase64Image();
$("#link2").attr("data-src", url);
}
});
</script>
After click download ajax function is used to store the image in a
location
<script type="text/javascript">
$(document).on("click","#link2",function() {
var image = $(this).attr('data-src');
if (image) {
$.ajax({
type: "post",
url: "generateImage",
cache: false,
data: {'image' : image},
success: function(json){
try{
var obj = jQuery.parseJSON(json);
if (obj['STATUS']) {
alert('Image save successfully');
} else {
alert('Something went wrong');
}
}catch(e) {
console.log('Exception while request..');
}
},
error: function(){
console.log('Error while request..');
}
});
}
});
</script>
Php code for store image in the folder
public function generateImage()
{
$image = $_POST['image'];
$folderPath = "uploads/";
$image_parts = explode(";base64,", $image);
$image_type_aux = explode("uploads/", $image_parts[0]);
$image_base64 = base64_decode($image_parts[1]);
$name = uniqid() . '.png';
$file = $folderPath . $name;
$output = file_put_contents($file, $image_base64);
if ($output) {
$status = array("STATUS"=>"true");
} else {
$status = array("STATUS"=>"false");
}
echo json_encode($status);
exit();
}
Source:stackexchange.com