How to Upload HTML Canvas Data to PHP Server

Last time, I shared my experience about how to use JavaScript saving HTML canvas data to local disk in Chrome. In this tutorial, I would like to share how to save HTML canvas data to remote service with JavaScript and PHP.

Dynamsoft Barcode Reader SDK
Ads Powered by Dynamsoft

Uploading canvas data is a little bit complicated comparing to file upload. If you want to learn how to upload a file, you can read the tutorial PHP File Upload.

Let’s get started to create a project, which includes two files upload.html and upload_data.php. In addition, you need to create a folder upload for receiving files.

upload.html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>Upload Canvas Data to PHP Server</title>
	</head>
	<body>
		<h1>Upload Canvas Data to PHP Server</h1>
		<canvas width="80" height="80" id="canvas">canvas</canvas>
		<script type="text/javascript">
			window.onload = function() {
				var canvas = document.getElementById("canvas");
				var context = canvas.getContext("2d");
				context.rect(0, 0, 80, 80);
				context.fillStyle = 'yellow';
				context.fill();
			}
		</script>

		<div>
			<input type="button" onclick="uploadEx()" value="Upload" />
		</div>

		<form method="post" accept-charset="utf-8" name="form1">
			<input name="hidden_data" id='hidden_data' type="hidden"/>
		</form>

		<script>
			function uploadEx() {
				var canvas = document.getElementById("canvas");
				var dataURL = canvas.toDataURL("image/png");
				document.getElementById('hidden_data').value = dataURL;
				var fd = new FormData(document.forms["form1"]);

				var xhr = new XMLHttpRequest();
				xhr.open('POST', 'upload_data.php', true);

				xhr.upload.onprogress = function(e) {
					if (e.lengthComputable) {
						var percentComplete = (e.loaded / e.total) * 100;
						console.log(percentComplete + '% uploaded');
						alert('Succesfully uploaded');
					}
				};

				xhr.onload = function() {

				};
				xhr.send(fd);
			};
		</script>
	</body>
</html>
  • Create a canvas tag, and draw a rectangle on canvas when the whole page has been loaded.
  • Create a button for triggering uploading event.
  • Create a form with a hidden input tag, which is used to save the data URL.
  • Use XMLHttpRequest to asynchronously upload form data to PHP service.

upload_data.php:

<?php
$upload_dir = "upload/";
$img = $_POST['hidden_data'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
$file = $upload_dir . mktime() . ".png";
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
?>

Now deploy the whole project to a web server, such as nginx, Apache and so forth. Visit localhost:port/upload.html, click the button, and open the file folder to check whether the image is there.

Anything unclear? Please feel free to contact me at {desmond at Dynamsoft dot com}.

  • Gegham Kocharyan

    Thanks Bro…. You helped me.

  • Thomas A.P.

    Nice and simple coding, Thanks Bro….very helpfull

  • Alejandro Lopez

    Nice and and simple code! Thank you so much…..

  • Kinetic Hammer

    image uploaded sucessfully
    after uploading how to show(disply) the uploaded file link

  • Kinetic Hammer

    thanks for your code it was very helpful

  • Wisam hakim

    It is really nice , but unfortunately , if the image is big the hidden file will not be enough and the image will not be complete send to server

  • Xanthig

    Thank you! I’ve been working on this for three days, and this worked within 5 minutes. You are wonderful!

  • TheWickedMan

    This… this is alot better the my first Found page given.

    And havent tested it but i already know this doesnt have any problems with $HTTP_RAW_POST_DATA

  • bahman

    so so so so soo tanks

    ilove youuuuuuuuuuu

  • olivier

    Perfect :) thank you Desmond

  • http://www.dynamsoft.com Desmond Shaw

    $finalUrl = “http://” . $_SERVER[‘SERVER_NAME’] . “/” . $file;

    echo $finalUrl;

  • olivier

    Work like a charm, thanks a lot! But how echo the final url please?

  • BOZAPE PEDRO BOZA

    Hi!
    The script is really great and help a lot but have a question.
    I am using in a testing server with an old php 5.2 version with no problems.
    But whe upload to my hosting server with php 5.5 the script dont work.
    I get no errors at all and the entire scripts seems to be executed.
    Just looks like the script is no loading the upload_data.php file.

    Any ideas or things I can do or test?

    My email is bozape@gmail.com

    I can send the test and hosting server address that I am using.

    Thanks!

  • gd

    Nice post, it really helped me a lot.