use OSS\Core\OssException;
use OSS\OssClient;
public function insert()
{
$file = request()->file('image');
$name=$file->getPathname();
// print_r($name);die();
//apikey
$apikey="BBmaz8XU1rKEHChQSqlsdCvG";
//SecretKey
$SecretKey="kmta1oDReXWWh2WOOhRlukL2PkcaIZGE";
//获取url
$url= "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={$apikey}&client_secret={$SecretKey}";
//获取到token;
$info= curlGet($url);
$token=$info['access_token'];
$url = 'https://aip.baidubce.com/rest/2.0/solution/v1/img_censor/v2/user_defined?access_token=' . $token;
$img = file_get_contents($name);
$img = base64_encode($img);
$bodys = array(
'image' => $img
);
$res = json_decode($this->curlPost($url, $bodys),true);
// print_r($res);die();
//根据自己的业务逻辑进行处理
if($res['conclusion']=='合规'){
// 接收文件数据
$file = request()->file('image');
// 取出文件名截取后缀
$name = $file->getOriginalName();
$suffix = strchr($name,'.');
// 阿里云配置
$accessKeyId = "LTAI5t7aTynkW97ncpUKqbyK";
$accessKeySecret = "orCDBYyRZlcseEqh7pZl6Af6HRTrin";
// Endpoint以杭州为例,其它Region请按实际情况填写。
$endpoint = "oss-cn-shanghai.aliyuncs.com";
// 设置存储空间名称。
$bucket= "ahao";
// 设置文件名称。
//这里是由sha1加密生成文件名 之后连接上文件后缀
$object = sha1(date('YmdHis', time()) . uniqid()) . $suffix;
$url = 'http://oss.lihao513.com/'.$object;
// <yourLocalFile>由本地文件路径加文件名包括后缀组成,例如/users/local/myfile.txt。
$filePath = $file->getPathname();
try{
$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
$result = $ossClient->uploadFile($bucket, $object, $filePath);
if(!$result){
return json(['status'=>1,'message'=>'上传失败']);
}else{
$arr['img']=$result['oss-request-url'];
Image::create($arr);
return json(['code'=>'200','msg'=>'成功','data'=>$url]);
}
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return false;
}
}else{
echo '图片不合规';
}
}
function curlPost($url = '', $param = '')
{
if (empty($url) || empty($param)) {
return false;
}
$postUrl = $url;
$curlPost = $param;
// 初始化curl
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $postUrl);
curl_setopt($curl, CURLOPT_HEADER, 0);
// 要求结果为字符串且输出到屏幕上
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
// post提交方式
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
// 运行curl
$data = curl_exec($curl);
curl_close($curl);
return $data;
}
|