Ajaxpost在服务器上有空值

我正在尝试从客户端收到的base64字符串中保存图像文件。

所以我有这个ajaxpost:

$.ajax({type: "POST", url: "upload_post.php", data: postData, dataType: "text", success: function(result){ alert("post result: " + result + " - data:" + postData); location.reload(); }}); 

这是postData一个例子(我知道它包含数据):

 {"ship_id":"407","base64_upload":"ABCSFSAFGDGFA....."} 

现在这是我的PHP代码处理这篇文章:

 $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()有关吗? 我该如何解决?

编辑

我通过对ajax数据执行JSON.parse(postData) ,将这些变量与实际数据一起发布。 现在我的问题是我仍然无法保存图像文件。 任何帮助?

这就是我为jQuery Post做的。 我希望它对你有所帮助

 $.post("upload_post.php", { ship_id: "407", base64_upload: "ABCSFSAFGDGFA....." }, function(data, status){ alert("post result: " + status+ " - data:" + data); location.reload(); }); 

你在php中获取的数据完全相同。

再一次,我正在回答我自己的问题。 问题是我已define('UPLOAD_DIR', 'news.site.com/docs/'.$id.'/'); 然后$file = UPLOAD_DIR . uniqid() . '.png'; $file = UPLOAD_DIR . uniqid() . '.png'; 这个UPLOAD_DIR目录并不存在。 所以我添加了一个检查是否存在,然后在创建文件之前创建了目录:

 $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.''; }