[英]Ajax post has empty values on the server
我正在尝试从客户端接收的base64字符串中保存图像文件。
所以我有这个ajax帖子:
$.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.'';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.