Laravel中使用GuzzleHttp调用Face++人脸识别接口

  1. 安装GuzzleHttp
//在composer.json中的require中添加
"guzzlehttp/guzzle": "^6.3",
//命令行执行
composer update
  1. 设置csrf验证过滤
  • 在app/Http/Middleware/VerifyCsrfToken.php中
protected $except = [
    '/upload',//要过滤的路由
    '/face02'
];
  1. 设置图片存储路径
  • 在config/filesystems.php(此时的存储目录为public/storage)
'public' => [
     'driver' => 'local',
     'root' => storage_path('/storage'),
     'url' => env('APP_URL').'/',
     'visibility' => 'public',
],
  1. 创建路由
Route::any('/face02', 'FaceController@detect');
Route::any('/upload','FaceController@upload');
  1. 创建控制器
<?php

namespace App\Http\Controllers;

use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use GuzzleHttp\Client;
use Jasongzj\LaravelQcloudImage\QcloudImage;
use Illuminate\Support\Facades\Storage;

class FaceController extends Controller
{
    public function detect(Request $request)
    {
        $client = new Client();

        $img = $request->input('img');

        try {
            $response = $client->request('POST', 'https://api-cn.faceplusplus.com/facepp/v3/detect', [
                'form_params' => [
                    'image_url' => $img,
                    'api_key' => 'YOUR API_KEY',
                    'api_secret' => 'YOUR API_SECRET',
                    'return_attributes' => 'emotion'
                ]
            ]);
            $body = $response->getBody();
            echo $body;
        } catch (GuzzleException $e) {

        }
        
    }

    public function upload(Request $request){
        if ($request->isMethod('POST')) {

            $fileCharater = $request->file('file');

            if ($fileCharater->isValid()) {

                //获取文件的扩展名
                $ext = $fileCharater->getClientOriginalExtension();

                //获取文件的绝对路径
                $path = $fileCharater->getRealPath();

                //定义文件名
                $filename = date('Y-m-d-h-i-s').'.'.$ext;

                //storage/app/public
                Storage::disk('public')->put($filename, file_get_contents($path));
            }
        }
        return 'storage/'.$filename;
    }
}

参考


作者:skyisbluening
原文:https://blog.csdn.net/weixin_38682852/article/details/79613812

猜你喜欢

转载自blog.csdn.net/qq_42094066/article/details/89930780