您的位置:首页 > 其它

base64数据如何传到后台

2016-12-13 13:18 127 查看
今天对接一个拼图的功能,最后生成的是一段base64的字符串,我用angularjs通过post将数据传到后台,结果接收不到:(其实一般可以接收到)

数据通过$_POST无法获取,如(xml数据、base64数据等)。

可以通过一下方式:

1、 $GLOBALS ["HTTP_RAW_POST_DATA"]

2、file_get_contents('php://input')

下面是我的两段代码,都是在thinkphp中实现的:

1、拼图的js代码:

       用angularjs通过post将数据传到后台

$scope.rasterize = function() {
if (!fabric.Canvas.supports('toDataURL')) {
alert('This browser doesn\'t provide means to serialize canvas to an image');
}
else {
$http({
url:'/Guide/Guide/mobilePT',
method:'POST',
headers:{'Content-Type':'application/x-www-form-urlencoded'},
data:canvas.toDataURL()  //canvas.toDataURL()是拼图功能最后传过来的数据
}).success(function(data){
location.href = "/Guide/Guide/puzzle_preview?image="+data;
});
}
};


php后台的处理

public function mobilePT(){
$data = file_get_contents("php://input");
if($data){
$img = str_replace('data:image/png;base64,','', $data);
//注意  此处不一定是 'data:image/png;base64,' 还可能是'data:image/jpeg;base64,'
//等等,所以在最好现在js中console.log('你的数据'),确定是什么类型的
$img = str_replace(' ','+', $img);//处理接收到的数据,否则图片会错误
$img = base64_decode($img);
$file_name = time().'_'.mt_rand().'.jpg';
$file = './data/runtime/puzzle';
if(!file_exists($file)) {
mkdir ($file, 0777, true );
}
$file = './data/runtime/puzzle/'.$file_name;
$arr = file_put_contents($file, $img);
$image= $file_name;
echo $image;
}else{
$this->assign('title','拼图');
$this->display();
}
}


2、截图的js代码:(这是一个截图插件最后也是生成base64)

       用js通过ajax的post方式将数据传到后台

var clipArea = new bjj.PhotoClip("#clipArea", {
size: [360, 120],
outputSize: [360, 120],
file: "#file",
view: "#view",
ok: "#clipBtn",
clipFinish: function(dataURL) {
$.ajax({
url: '{:U("Guide/Guide/guide_info")}',//ajax提交路径
type: 'post',//提交方式
data: { image: dataURL},//提交参数
success: function (result){
history.go(0);
},
error: function () {
history.go(0);
}
});
}
});


php后台代码,此处用的是post接受的数据

public function guide_info(){
$id = session('userid');
$model = D('guide_info');
if($_POST['image']){
$img = str_replace('data:image/jpeg;base64,','', $_POST['image']);
$img = str_replace(' ','+', $img);
$img = base64_decode($img);
$file_name = time().'_'.mt_rand().'.jpg';
$file = './public/face/'.$file_name;
$_POST['avatar'] = $file_name;
unset($_POST['image']);
$arr = file_put_contents($file, $img);
if($arr){
echo json_encode(1);
}else{
echo json_encode(0);
}
}
}


1、拼图的js代码:

       用angularjs通过post将数据传到后台
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: