当前位置: 代码网 > it编程>编程语言>Php > PHP传输base64数据不完整的解决方法

PHP传输base64数据不完整的解决方法

2024年06月10日 Php 我要评论
前言最近在做ocr增值税务处理时,接口是通过图片转base64提交处理然后返回数据的,我通过前端将图片转换为base64提交到后端接收时,通过在线工具进行测试,发现传递过去的数据可以使用,接收到的数据

前言

最近在做ocr增值税务处理时,接口是通过图片转base64提交处理然后返回数据的,我通过前端将图片转换为base64提交到后端接收时,通过在线工具进行测试,发现传递过去的数据可以使用,接收到的数据却提示损坏

解决办法

<?php
header('content-type: text/html; charset=utf-8');
header('access-control-allow-origin: *'); // 允许任何网址请求
header('access-control-allow-methods: post, get, options, delete'); // 允许请求的类型
header('access-control-allow-credentials: true'); // 设置是否允许发送 cookies
header('access-control-allow-headers: content-type, content-length, accept-encoding, x-requested-with, origin'); // 设置允许自定义请求头的字段


// 接收post数据

$base64=$_post['base'];

替换为以下代码:

<?php
header('content-type: text/html; charset=utf-8');
header('access-control-allow-origin: *'); // 允许任何网址请求
header('access-control-allow-methods: post, get, options, delete'); // 允许请求的类型
header('access-control-allow-credentials: true'); // 设置是否允许发送 cookies
header('access-control-allow-headers: content-type, content-length, accept-encoding, x-requested-with, origin'); // 设置允许自定义请求头的字段


// 接收post数据
$postdata = file_get_contents('php://input');
$base64=urldecode($postdata);
$new_base64 = substr($base64, 27); 

即可解决

拓展知识

base64解码后的图片显示不完整问题

base64解码后的图片显示不完整

从前端获取base64信息就后用以下代码进行处理,发现解析出来的图片会损坏。

stringbuffer filepathstr=new stringbuffer();
			for(int i=0;i<filelist.size();i++){
				jsonobject fileobj = filelist.getjsonobject(i);
				if(null!=fileobj){
					string filecontent=fileobj.getstring("filecontent");
					string filename=fileobj.getstring("filename");
					//base64解码  
					byte[] bytes=base64.decodebase64(filecontent);
					  for (int j = 0; j < bytes.length; ++j) {  
					        if (bytes[j] < 0) {// 调整异常数据  
					        	bytes[j] += 256;  
					        }  
					  }

导致损坏可能为以下原因

一:需要去掉如下头部信息。

二:

因为ajax在传输过程中加号会变成空格而base64里是有加号的,所以在ajax传输前先要对base64进行编码,把加号替换成%2b的url编码。
var img = imagedata.replace(/+/g,"%2b");
imagedata就是原始的base64码

以上就是php传输base64数据不完整的解决方法的详细内容,更多关于php base64数据不完整的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com