Ajax帖子在服务器上具有空值 [英] Ajax post has empty values on the server
问题描述
我正在尝试从客户端接收的base64字符串中保存图像文件.
I'm trying to save an image file out of a base64 string received from the client side.
所以我有这个ajax帖子:
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();
}});
这是postData
(我知道其中包含数据)的示例:
Here is an example of postData
(which I know contains data):
{"ship_id":"407","base64_upload":"ABCSFSAFGDGFA....."}
现在这是处理该帖子的我的php代码:
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.'';
问题是$ _POST变量始终为空.这是为什么? json相关吗? location.reload()相关吗?以及如何解决?
The problem is the $_POST variables are always empty. why is that? json related? location.reload() related? and how do I fix it?
编辑
通过对ajax数据执行JSON.parse(postData)
,我将这些变量与实际数据一起发布.现在我的问题是我仍然无法保存图像文件.有帮助吗?
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?
推荐答案
我再次回答了自己的问题.
问题是我有define('UPLOAD_DIR', 'news.site.com/docs/'.$id.'/');
然后$file = UPLOAD_DIR . uniqid() . '.png';
,此UPLOAD_DIR
目录实际上并不存在.因此,我添加了一个检查是否存在,然后在创建文件之前创建了目录:
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.'';
}
这篇关于Ajax帖子在服务器上具有空值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!