I know that a similar question has been asked before but none of them helped me. up vote
I have written some JavaScript that allows the user to draw on the canvas in different colors and pen sizes. I want to upload the canvas to my server
This is my index.html:
<html>
<head>
</head>
<body>
<canvas id="canvas"></canvas>
<button id="button_clear" onclick="test()">Clear/upload canvas</button>
<script>
function test(){
var canvas = document.getElementById("canvas");
var dataURL = canvas.toDataURL();
$.ajax({
type: "POST",
url: "script.php",
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
});
}
</script>
script.php:
<?php
// requires php5
//define('UPLOAD_DIR', 'FBdraw/');
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
When I refresh the script.php page it saves a empty 0 kB image.
Related
I need to have the child image appear in a new division it places it outside the HTML tag and cuts off bottom on save any suggestions?
I was able to get Clone to work TY for that advise... But my upload is still missing app. 50 pixels from bottom of image ..... Still have not figured out how to return the image URL back and would like to get the clone to appear Directly under my generated image and not off page..... any advise on that?
function screenshot(){
html2canvas(document.getElementById("capture")).then(function(canvas) {
var elmnt = document.getElementsByTagName("DIV")[2];
var cln = elmnt.cloneNode(true);
document.body.appendChild(cln);
// Get base64URL
var base64URL = canvas.toDataURL('image/jpg').replace('image/jpg', 'image/octet-stream');
// AJAX request
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {image: base64URL},
success: function(data){
console.log('Upload successfully.');
}
});
});
}
Here is my ajaxfile
$image = $_POST['image'];
$location = "upload/";
$image_parts = explode(";base64,", $image);
$image_base64 = base64_decode($image_parts[1]);
date_default_timezone_set("America/Chicago");
$filename = date("m_j_y-H_i_s").'.png';
$file = $location . $filename;
$imageurl = 'upload/'.$filename.'.png';
file_put_contents($file, $image_base64);
echo $filename;
echo $file;
echo $location;
echo $image;
I have a canvas image on my page with a Save button that saves down a PNG image file.
function save() {
var canvas = document.getElementById('drawing');
var dataURL = canvas.toDataURL();
$.ajax({
type: "POST",
url: "canvas_ajax_upload_post.php",
data: { img: dataURL }
}).done(function(msg){
alert(msg);
});
}
The canvas_ajax_upload_post.php looks like this:
<?php
$img = $_POST['img'];
if (strpos($img, 'data:image/png;base64') === 0) {
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = 'uploads/img'.date("YmdHis").'.png';
if (file_put_contents($file, $data)) {
echo "The canvas was saved as $file.";
} else {
echo 'The canvas could not be saved.';
}
}
?>
This works fine, images get saved to the uploads folder on my server. What I have been trying to do is store the filename in my SQL database. I have a hidden form field on my main page that I would like to pass the filename or filepath to after the image has been saved, but I cannot figure out how.
I have tried embedding JavaScript code in the PHP file, but it just treats it as a text string and includes it in the alert popup. Essentially what I am trying to do is use the $file variable from the php file in JavaScript code.
E.g. document.getElementById("hidden_form_field").value = $file;
Can anybody help?
You can pass the filename in the data object:
function save() {
var canvas = document.getElementById('drawing');
var dataURL = canvas.toDataURL();
$.ajax({
type: "POST",
url: "canvas_ajax_upload_post.php",
data: {
img: dataURL,
filename: document.getElementById("hidden_form_field").value
}
}).done(function(msg){
alert(msg);
});
}
Then retrieve the "filename" variable by getting $_POST["filename"]:
<?php
$img = $_POST['img'];
$filename = $_POST['filename'];
if (strpos($img, 'data:image/png;base64') === 0) {
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = 'uploads/img'.date("YmdHis").'.png';
if (file_put_contents($file, $data)) {
echo "The canvas was saved as $file.";
} else {
echo 'The canvas could not be saved.';
}
// DO SOME SQL QUERY W/ $filename variable
// SQL CODE HERE
}
?>
You'll need include your SQL query code to use the $filename variable. I didn't see that code in your question.
By what I understand from your question, you're trying to get the value of $file back form php.
You can return the value via the msg variable (which is what php echos) in your $.ajax.done function.
For example:
function(msg){
alert(msg);
if(msg.search("The canvas was saved as")!=-1){//was saved
document.getElementById("hidden_field").value=msg.slice(23);//assuming string "The canvas was saved as $file."
}
}
I have this function from a GitHub repo that outputs a drawn signature on canvas to a DataURL(). When I inspect it, it comes back as a string of encoded data(a .png).
The user clicks the save button and this happens:
saveButton.addEventListener("click", function (event) {
if (signaturePad.isEmpty()) {
alert("Please provide signature first.");
} else {
saveSignature(signaturePad.toDataURL());
}
});
function saveSignature(dataURL) {
$.ajax({
type: "POST",
datatype: "json",
url: "script.php",
data: {
imgBase64: dataURL
}
}).done(function(o) {
console.log('saved');
});
signaturePad.clear();
}
Then it triggers a PHP script in the same folder, called script.php.
<?php
// requires php5
define('UPLOAD_DIR', 'images');
$img = $_POST['imgBase64'];
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
I can't find out why it's causing a 500 server error.
The console isn't printing 'unable to save file', nor 'saved.'
You have error in script.php you are receving data in $img while write using $data so need to replace variable
<?php
// requires php5
define('UPLOAD_DIR', 'images');
$img = $_POST['imgBase64'];
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $img); //<---- change here
print $success ? $file : 'Unable to save the file.';
?>
I want to upload an image when the user clicks a button(#myid.save).Below is my code:
HTML Code:
<canvas id="cnv" width="500" height="100"></canvas>
<input id="myid_save" type="submit">Save</input>
JavaScript Code:
$('#myid_save').on('click', function(e) {
e.preventDefault();
saveViaAJAX();
});
function saveViaAJAX()
{
var testCanvas = document.getElementById("cnv");
var canvasData = testCanvas.toDataURL("image/png");
//var postData = "canvasData="+canvasData;
$.ajax({
type: "POST",
url: "testSave.php",
data: {
imgBase64: canvasData
}
}).done(function(o) {
console.log('saved');
});
}
testSave.php File:
<?php
define('UPLOAD_DIR', 'C:\xampp\htdocs\drupal-7.34\sites\all\modules\myid\uploads\id_signature');
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . '\sample.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
My console says "saved" but there's no image saved in my server. Where am I missing?
testSave.php references $_POST['canvasData'], but the JS sends the intended variable as imgBase64. That line should instead read $img = $_POST['imgBase64'] in order to match the AJAX.
Can anybody help me with this I'm solving this problem for almost a week and never get success. I want to happen is to call the image that was been created the image goes to "image" in a div and I want to call that image to the another page but No image show. Please take a look my code.
<script>
function myFunction(){
html2canvas([document.getElementById('card-container')], {
onrendered: function (canvas) {
var data = canvas.toDataURL('image/png');
// AJAX call to send `data` to a PHP file that creates an image from the dataURI string and saves it to a directory on the server
var image = new Image();
image.src = data;
document.getElementById('image').appendChild(image);
}
});
}
</script>
<button onclick="myFunction()" >Try it</button>
<div id="image">
<p>Image:</p>
</div>
<form enctype="multipart/form-data" action="sample.com" method="post" onsubmit="this.divcontent.value = document.getElementById('image').innerHTML;" >
<input type="hidden" name="image" id="divcontent" value="" />
<input type="submit" value="Submit" />
</form>
Here is the ready-image.php
<?php
$img = $_POST['divcontent'];
echo "<img src='$img' alt='image' />";
define('UPLOAD_DIR', 'wp-content/uploads/2014/03/');
$img = $_POST['img'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
Please help me guys. Thank you very much.
I am not sure if this is what you want. Since the ajax part is missing from your code, I am just trying to pass the image captured to the ready-image.php and display it.
I am assuming that the codes are on 2 separate files.
<script>
function myFunction() {
html2canvas([document.getElementById('card-container')], {
onrendered: function (canvas) {
var data = canvas.toDataURL('image/png');
var image = new Image();
image.src = data;
document.getElementById('image').appendChild(image);
$("#divcontent").val(data); //save the image base64 string to a hidden input
}
});
}
</script>
<div id="card-container">
<button onclick="myFunction()" >Try it</button>
<div id="image">
<p>Image:</p>
</div>
<form action="ready-image.php" method="POST">
<input type="hidden" name="divcontent" id="divcontent" />
<input type="submit" value="Submit" />
</form>
</div>
ready-image.php:
<?php
$img = $_POST['divcontent'];
echo "<img src='$img' alt='image' />";
define('UPLOAD_DIR', 'wp-content/uploads/2014/03/');
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = UPLOAD_DIR . uniqid() . '.png';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>
Update:
<?php
$img = $_POST['divcontent'];
echo "<img src='$img' alt='image' />";
define('UPLOAD_DIR', 'wp-content/uploads/2014/03/');
$filteredData = substr($img, strpos($img, ",") + 1);
$decodedData = base64_decode($filteredData);
$file = UPLOAD_DIR . uniqid() . '.png';
$fp = fopen($file,'wb');
if ($fp) {
fwrite($fp, $decodedData);
print $file;
} else {
print 'Unable to save the file.';
}
fclose($fp);
?>
I commented out the download part because I am not sure how exactly you call the ajax to save the file, so that part is omitted from my solution.