百度小程序第三方接入图片上传demo

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

代码是基于ThinkPHP 3.2的,其他语言请自行实现,PHP版本为5.6

/**
* 图片上传
* @Author Qianlong <[email protected]>
* @PersonSite http://dev.21ds.cn/
*/ 
public function onlyUploadImage()
 {
 $upload = new \Think\Upload(); // 实例化上传类
 $upload->maxSize   =     3145728; // 设置附件上传大小
 $upload->exts      =     array('jpg', 'bmp', 'png', 'jpeg'); // 设置附件上传类型
 $upload->rootPath  =     './Uploads/'; // 设置附件上传根目录
 $upload->savePath  =     ''; // 设置附件上传(子)目录
 // 上传文件 
 $info   =   $upload->upload();
 $access_token = $this->applet->getAccessToken();
 $filename = '/webroot/Uploads/' . $info['file']['savepath'] . $info['file']['savename'];
 $postd['access_token'] = $access_token;
 $postd['type'] = 2;
 $file['realpath'] = $filename;
 $file['name'] = 'multipartFile';
 $file['type'] = $info['file']['type'];
 $status = $this->Https_request('https://openapi.baidu.com/file/2.0/smartapp/upload/image',  $postd,null, $file);
 if (!empty($status)) {
 switch ($status['errno']) {
 case '0':
 $returnData['code'] = 200;
 $returnData['data'] = $status['data'];
 $returnData['msg'] = '上传成功';
 $this->BspReturn($returnData);
 break;
 case '47003':
 $returnData['code'] = -1;
 $returnData['data'] = '';
 $returnData['msg'] = '图片格式无效';
 $this->BspReturn($returnData);
 break;
 case '47000':
 $returnData['code'] = -1;
 $returnData['data'] = '';
 $returnData['msg'] = '图片格式无效';
 $this->BspReturn($returnData);
 break;
 default:
 $returnData['code'] = -1;
 $returnData['data'] = $status;
 $returnData['msg'] = '上传失败,请重试';
 $this->BspReturn($returnData);
 break;
 }
 } else {
 $returnData['code'] = -1;
 $returnData['data'] = $status;
 $returnData['msg'] = '上传失败,请重试';
 $this->BspReturn($returnData);
 }
 }
 public function Https_request($url,  $data = null, $cookie = null, $file = null, $header = '')
 {
 $curl = curl_init();
 curl_setopt($curl, CURLOPT_URL, $url);
 curl_setopt(
 $curl,
 CURLOPT_SSL_VERIFYPEER,
 FALSE
 );
 curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
 //携带cookie文件
 if (!empty($cookie)) {
 curl_setopt($curl, CURLOPT_COOKIEFILE, $cookie); //读取cookie
 }

 //携带头
 if (!empty($header)) {
 curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
 }

 //上传文件
 if (!empty($file)) {
 $file_obj = new \CURLFile($file['realpath'], $file['type']);
 $data["{$file['name']}"] = $file_obj;
 }

 //发送post数据
 if (!empty($data) && !isset($file_obj)) {
 curl_setopt($curl, CURLOPT_POST, 1);
 curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($data));
 } elseif (!empty($data)) {
 curl_setopt($curl, CURLOPT_POST, 1);
 curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
 }
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
 $output = curl_exec($curl);

 if (empty($output)) return 'no data';
 curl_close($curl);
 return is_null(json_decode($output)) ? $output : json_decode($output, true);
 }

文章来源:http://dev.21ds.cn/article/300.html

转载于:https://my.oschina.net/devqianlong/blog/3052079

你可能感兴趣的:(百度小程序第三方接入图片上传demo)