php实现base64编码1003无标题,php无法解码js发过来的base64图片编码,有诡异空格

我通过vue的axois通过post方法向php转图片编码,在php base64_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);

...

c8129434632d363c6877f4be0e8017d0.png

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解码即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值