I'm trying to save an image file out of a base64 string received from the client side.
So I have this ajax post:
$.ajax({type: "POST", url: "upload_post.php", data: postData, dataType: "text", success: function(result){
alert("post result: " + result + " - data:" + postData);
location.reload();
}});
Here is an example of postData
(which I know contains data):
{"ship_id":"407","base64_upload":"ABCSFSAFGDGFA....."}
Now here is a my php code that handles this post:
$id = $_POST['ship_id'];
$img = $_POST['base64_upload'];
define('UPLOAD_DIR', 'news.site.com/docs/'.$id.'/');
$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. '.$file.'';
The problem is the $_POST variables are always empty. why is that? json related? location.reload() related? and how do I fix it?
EDIT
I have got these variables posted with actual data by doing JSON.parse(postData)
on the ajax data. Now my problem is I still can't save the image file. any help?
Once again, I'm answering my own question. The problem was I have define('UPLOAD_DIR', 'news.site.com/docs/'.$id.'/');
and then $file = UPLOAD_DIR . uniqid() . '.png';
and this UPLOAD_DIR
directory doesn't really exists. So I added a check if it exists and then created the directory before creating the file:
$id = $_POST['ship_id'];
$img = $_POST['base64_upload'];
define('UPLOAD_DIR', 'news.site.com/docs/'.$id.'/');
$file2 = UPLOAD_DIR;
if(!file_exists($file2)){
mkdir($file2, 0777, true);
$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. '.$file.'';
}
This is what I do for jQuery Post. I hope it helps you
$.post("upload_post.php",
{
ship_id: "407",
base64_upload: "ABCSFSAFGDGFA....."
},
function(data, status){
alert("post result: " + status+ " - data:" + data);
location.reload();
});
You fetch the data in php exactly the same.