douyangcheng4965 2017-03-15 23:35
浏览 37
已采纳

Ajax帖子在服务器上有空值

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?

  • 写回答

2条回答 默认 最新

  • douyi6290 2017-03-16 16:08
    关注

    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.'';
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?