php对接 星火知识库-文件上传及签名
/**
* @throws \GuzzleHttp\Exception\GuzzleException
*/
public function fileUpload(Request $request)
{
$file = $request->file('file');
if (empty($file)) {
return json_encode(['code'=>201, 'msg' => '文件不能为空']);
}
if (!in_array($file->clientExtension(), ['doc','docx','pdf','md','txt'])) {
return json_encode(['code'=>201, 'msg' => '只允许上传doc/docx、pdf、md、txt 格式的文件']);
}
if ($file->getSize() > 1024 * 20) {
return json_encode(['code'=>201, 'msg' => '单文件大小不能超过 20MB']);
}
$time = time();
$auth = md5(self::APP_ID.$time);
$text = utf8_encode($auth);
$rawHmac = hash_hmac('sha1', $text, self::API_SECRET, true);
$signature = base64_encode($rawHmac);
$data = fopen($_FILES['file']['tmp_name'],'r+');
$fileUploadApi = 'https://chatdoc.xfyun.cn/openapi/fileUpload';
$param = [
'headers' => [
'appId' => self::APP_ID,
'timestamp' => $time,
'signature' => $signature,
],
'multipart' => [
[
'name' => 'file',
'contents' => $data,
'header' => [
'content-type'=> 'multipart/form-data'
],
'filename' => $_FILES['file']['name']
]
]
];
$client = new \GuzzleHttp\Client();
try {
$data = $client->request('post',$fileUploadApi, $param);
$data = $data->getBody()->getContents();
} catch (\Throwable $exception) {
return json_encode(['code'=> 201, 'msg'=> $exception->getMessage()]);
}
$data = json_decode($data, true);
return $data;
}