I have a HTML file with some images as below:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Chapter 4 : Data Types - Data URI </title>
<script type="text/javascript"></script>
</head>
<body>
<input type="button" value="Test" text="Button" onclick="UploadStart()"/>
<img id="tst" src="1.png">
<img id="tst" src="2.png">
</body>
From this Page i am taking the images with Javascript as below :
UploadStart Function
function UploadStart(){
if (window.File && window.FileReader && window.FileList && window.Blob) {
sendRequest(MakeBase64());
} else {
alert('The File APIs are not fully supported in this browser.');
}
}
Base64 Conversion Method
function MakeBase64(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("tst");
ctx.drawImage(img, 20, 20);
var dataURL = c.toDataURL("image/png");
var blob = dataURItoBlob(dataURL);
return blob;
}
sendRequest
function sendRequest(data)
{
var xhr = createXHR();
if (xhr){
var url = "http://localhost/AjaxFormProcessing/AJAXIMG/server.php";
var payload = "image=" + data;
xhr.open("POST",url + "?" + payload,true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded ');
xhr.onreadystatechange = function(){handleResponse(xhr);};
xhr.send(null);
}
}
Server.php
<?php
$data = $_REQUEST['image'];
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$data=base64_decode($data);
$file = 'uploads/'. uniqid() . '.png';
$success = file_put_contents($file, $data);
if($success){echo "Success";}
else {echo "Failed";}
?>
I am getting Success on my Client Side. But The image getting saved is only 1KB always and has no data in it. Means it's blank image. What's wrong going on ??