问题:app上传头像,php作为api端应该如何接收图片信息?

上传部分的代码不是问题,主要是server端如何才能接收到APP端的图片信息。在B/S架构下,可以直接通过form表单设置enctype="multipart/form-data",$_FILES数组中就有了图片信息。那么在C/S模式中,也是如此吗? (推荐学习:PHP视频教程)
解答1(见方式一): 一般是采用二进制流传输,客户端传的是二进制,服务器端接收,然后file_put_contents写入文件就可以了。文件名格式,文件放哪里,这些自己定义。
解答2(见方式二):Android或者IOS客户端模拟一个HTTP的Post请求到服务器端,服务器端接收相应的Post请求后(通过$_FILES获取图片资源),返回响应信息给给客户端。(这一种方式和获取Html方式提交的方法一样)
立即学习“PHP免费学习笔记(深入)”;
把图片进行base64加密成字符串,进行传输
说明:IOS或者安卓端:通过把图片进行base64编码得到字符串,传给接口
接口端:把接收的字符串进行base64解码,再通过file_put_contents函数,上传到指定的位置
/**
* 图片上传
* @param $imginfo - 图片的资源,数组类型。['图片类型','图片大小','图片进行base64加密后的字符串']
* @param $companyid - 公司id
* @return mixed
*/
public function uploadImage( $imginfo , $companyid ) {
$image_type = strip_tags($imginfo[0]); //图片类型
$image_size = intval($imginfo[1]); //图片大小
$image_base64_content = strip_tags($imginfo[2]); //图片进行base64编码后的字符串
$upload = new UploaderService();
$upconfig = $upload->upconfig;
if(($image_size > $upconfig['maxSize']) || ($image_size == 0)) {
$array['status'] = 13;
$array['comment'] = "图片大小不符合要求!";
return $array;
}
if(!in_array($image_type,$upconfig['exts'])) {
$array['status'] = 14;
$array['comment'] = "图片格式不符合要求!";
return $array;
}
// 设置附件上传子目录
$savePath = 'bus/group/' . $companyid . '/';
$upload->upconfig['savePath'] = $savePath;
//图片保存的名称
$new_imgname = uniqid().mt_rand(100,999).'.'.$image_type;
//base64解码后的图片字符串
$string_image_content = base64_decode($image_base64_content);
// 保存上传的文件
$array = $upload->upload($string_image_content,$new_imgname);
return $array;
}// 上传配置信息
public $upconfig = array(
'maxSize' => 3145728, //3145728B(字节) = 3M
'exts' => array('jpg', 'gif', 'png', 'jpeg'),
// 'rootPath' => './Public/Uploads/info/',
'rootPath' => 'https://www.eyuebus.com/Public/Uploads/info/',
);
/**
* @param $string_image_content - 所要上传图片的字符串资源
* @param $new_imgname - 图片的名称,如:57c14e197e2d1744.jpg
* @return mixed
*/
public function upload($string_image_content,$new_imgname) {
$res['result'] = 1;
$res['imgurl'] = '';
$res['comment'] = '';
do {
$ret = true;
$fullPath = $this->upconfig['rootPath'] . $this->upconfig['savePath'];
if(!file_exists($fullPath)){
$ret = mkdir($fullPath, 0777, true);
}
if(!$ret) {
// 上传错误提示错误信息
$res['result'] = 12;
$res['comment'] = "创建保存图片的路径失败!";
return $res;
break;
}
//开始上传
if (file_put_contents($fullPath.$new_imgname, $string_image_content)){
// 上传成功 获取上传文件信息
$res['result'] = 0;
$res['comment'] = "上传成功!";
$res['imgname'] = $new_imgname;
}else {
// 上传错误提示错误信息
$res['result'] = 11;
$res['comment'] = "上传失败!";
}
} while(0);
return $res;
}以上就是php接口如何传输图片的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号