我通过vue的axois通过post方法向php转图片编码,在phpbase64_decode解码的时候总是失败
发现:
在php里,base64编码里的'+'号变成了空格
尝试用str_replace('','+',$str)失败,无法替换
尝试用str_replace('','%2B',$str)成功替换,还是无法解码
对比初始的base64编码和替换后的编码发现中间少了几行(我认为原因就出在这里)
后面尝试
(1)在js里先将'+'号替换到'-',再在php里替换回来,同样上面3和4
(2)在js里使用encodeURIComponent,再在php里解码回来,同样上面3和4
啊啊啊,我主要是做前端的,php这方面不是很熟悉,查了很久资料都没找到解决方法,相当难受
代码:
JavaScript:
...this.$http.post('../info/publish.php',{name:this.name,description:this.description,cid:this.fenlei,price:this.price,image:this.base64,address:this.location}).then((res)=>{//console.log(this.base64);console.log(res.data);});...
PHP:
...$data=file_get_contents('php://input');$pName=json_decode($data)->name;$pDe=json_decode($data)->description;$cid=json_decode($data)->cid;$price=json_decode($data)->price;$image=json_decode($data)->image;$image1=str_replace('','+',$image);//$image=urldecode($image);$address=json_decode($data)->address;$image=substr(strstr($image1,','),1);$img=base64_decode($image);...
post数据是没必要encode的
我觉得这是php的锅,base64转码之后的图片,php解码应该是解码'data:image/png;base64,'后面的一串代码
$img=substr('img数据',22);file_put_contents('path',base64_decode($img));
你在前端先把base64字符串中+
号替换为%2B
,然后php接收的时候再对base64串做urldecode(base64)
解码试试
前端url编码后,在php那层没必要url解码,中间件如apache会自动解码的,包括post。
因此解决办法是js直接url编码image数据,后端php正常base64解码即可。