I'm trying to send an image from user's computer using an input (file). I resize the image using a canvas and then get a base64 string encoded via the toDataURL method of the canvas.
Then I send the encoded string to my server via an AJAX request. In PHP, I receive properly the POST data, but it fails when I want to use the base64_decode to save the encoded string into a file on my server.
CLIENT SIDE :
function upload_document(file){
var url_post_document = "url_to_server";
var type_img = file.type;
var reader = new FileReader();
reader.onload = function(evt){
var image = document.createElement('img');
image.onload = function (){
var canvas = document.createElement('canvas');
canvas.height = 40;
canvas.width = 40;
var ctx = canvas.getContext('2d');
ctx.drawImage(this, 0, 0, 40, 40);
var shrinked = canvas.toDataURL(file.type);
//console.log(shrinked);
$.ajax({
url: url_post_document,
type: 'POST',
xhrFields: {
withCredentials: false
},
data: {
"user_id": user_id,
"image": shrinked,
"image_type": type_img
},
success: function(data) {
console.log("RESPONSE");
console.log(data);
},
error: function() {
console.log("----- FAIL -----");
},
complete: function() {
console.log("----- REQUEST COMPLETED -----");
}
});
};
image.src = reader.result;
};
reader.readAsDataURL(file);
}
SERVER SIDE :
if(isset($_POST['user_id'])){
$extension = explode('/', $_POST['image_type']);
$extension = $extension[1];
define('UPLOAD_DIR', WP_CONTENT_DIR.'/uploads/userthumb/');
$imgBaseData = rtrim($_POST['image']);
$img = str_replace('data:'.$_POST['image_type'].';base64,', '', $imgBaseData);
$img = str_replace(' ', '+', $img);
$baseimage = base64_decode($img, true);
return $baseimage;
}
I tried to copy and past the base64 string got from the toDataURL method on an online base64decoder and it works, the image is displayed. But on the server, impossible to decode the string.
I would appreciate any help on this matter. Thanks in advance !