javascript - php无法解码js发过来的base64图片编码,有诡异空格

 mobiledu2502878025 发布于 2022-11-28 09:49

我通过vue的axois通过post方法向php转图片编码,在phpbase64_decode解码的时候总是失败

发现

  1. 在php里,base64编码里的'+'号变成了空格

  2. 尝试用str_replace('','+',$str)失败,无法替换

  3. 尝试用str_replace('','%2B',$str)成功替换,还是无法解码

  4. 对比初始的base64编码和替换后的编码发现中间少了几行(我认为原因就出在这里)

  5. 后面尝试
    (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);...

4 个回答
  • post数据是没必要encode的

    2022-11-28 09:53 回答
  • 我觉得这是php的锅,base64转码之后的图片,php解码应该是解码'data:image/png;base64,'后面的一串代码

    $img=substr('img数据',22);file_put_contents('path',base64_decode($img));
    2022-11-28 09:53 回答
  • 你在前端先把base64字符串中+号替换为%2B,然后php接收的时候再对base64串做urldecode(base64)解码试试

    2022-11-28 09:53 回答
  • 前端url编码后,在php那层没必要url解码,中间件如apache会自动解码的,包括post。
    因此解决办法是js直接url编码image数据,后端php正常base64解码即可。

    2022-11-28 09:53 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有