diff --git a/app/api/controller/XunFeiController.php b/app/api/controller/XunFeiController.php index cc10332fa..fb570235b 100644 --- a/app/api/controller/XunFeiController.php +++ b/app/api/controller/XunFeiController.php @@ -226,6 +226,10 @@ class XunFeiController extends BaseApiController } } } else { + // 删除临时音频文件 + if (file_exists($file)) { + //unlink($file); + } return $this->fail('无法连接到 WebSocket 服务器'); } fclose($audioFile); @@ -274,7 +278,6 @@ class XunFeiController extends BaseApiController public function ocr() { $ocrHostUrl = "https://api.xf-yun.com/v1/private/sf8e6aca1"; - $base64_image = request()->param('base64_image'); $file = request()->file('image'); if (empty($file)) { return $this->fail('未上传图片文件'); @@ -293,41 +296,51 @@ class XunFeiController extends BaseApiController $base64_image = base64_encode(file_get_contents($file)); $ocr = new OcrClient($this->app_id, $this->api_key, $this->api_secret); $authorization = $ocr->assembleAuthorization($ocrHostUrl); - $requestBody = "{ - 'header': { - 'app_id': '{$this->app_id}', - 'status': 3 - }, - 'parameter': { - 'sf8e6aca1': { - 'category': 'ch_en_public_cloud', - 'result': { - 'encoding': 'utf8', - 'compress': 'raw', - 'format': 'json' - } - } - }, - 'payload': { - 'sf8e6aca1_data_1': { - 'encoding': '{$ext}', - 'status': 3, - 'image': '{$base64_image}' - } - } - }"; - $ocrHostUrl .= '?authorization=' . $authorization; + $requestBody = [ + 'header' => [ + 'app_id' => $this->app_id, + 'status' => 3 + ], + 'parameter' => [ + 'sf8e6aca1' => [ + 'category' => 'ch_en_public_cloud', + 'result' => [ + 'encoding' => 'utf8', + 'compress' => 'raw', + 'format' => 'json' + ] + ] + ], + 'payload' => [ + 'sf8e6aca1_data_1' => [ + 'encoding' => $ext, + 'status' => 3, + 'image' => $base64_image + ] + ] + ]; + $ocrHostUrl .= '?authorization=' . $authorization; + $responseData = ''; try { $client = new GzClient(['timeout' => 2]); $response = $client->request('POST', $ocrHostUrl, [ - 'json' => json_decode($requestBody, true), + 'json' => $requestBody, 'verify' => false ]); $responseData = $response->getBody()->getContents(); - return $this->data(['words' => (string)$responseData]); + if (file_exists($file)) { + // 删除临时文件 + unlink($file); + } } catch (GuzzleException $e) { + if (file_exists($file)) { + // 删除临时文件 + unlink($file); + } return $this->fail($e->getMessage()); } + + return $this->data(['words' => (string)$responseData]); } }