Files
miniapi/app/miniapi/controller/Upload.php
gaofeng 1f854b73f7 提交
2026-08-13 10:09:22 +08:00

97 lines
3.0 KiB
PHP

<?php
declare (strict_types=1);
namespace app\miniapi\controller;
use app\service\SwooleService;
class Upload extends Base
{
public function image()
{
$scene = strtolower(trim((string)$this->request->post('scene', '')));
$contactUserId = 0;
if (in_array($scene, ['passport', 'id_card'], true)) {
$login = $this->requireLogin();
if (!is_int($login)) {
return $login;
}
$contactUserId = $login;
}
$file = request()->file('file');
if (!$file) {
return $this->uploadResponse(0, '请上传图片');
}
$path = $file->getPathname();
if (!is_file($path)) {
return $this->uploadResponse(0, '上传文件读取失败');
}
$size = filesize($path);
if ($size === false || $size <= 0) {
return $this->uploadResponse(0, '上传文件为空');
}
if ($size > 10 * 1024 * 1024) {
return $this->uploadResponse(0, '图片不能超过10MB');
}
$originalName = (string)($_FILES['file']['name'] ?? 'upload.jpg');
$ext = strtolower(pathinfo($originalName, PATHINFO_EXTENSION));
$ext = $ext === 'jpeg' ? 'jpg' : $ext;
if (!in_array($ext, ['jpg', 'png', 'gif', 'webp', 'bmp'], true)) {
return $this->uploadResponse(0, '请上传图片文件');
}
$mime = function_exists('mime_content_type') ? (string)mime_content_type($path) : '';
if ($mime !== '' && strpos($mime, 'image/') !== 0) {
return $this->uploadResponse(0, '请上传图片文件');
}
$content = file_get_contents($path);
if ($content === false || $content === '') {
return $this->uploadResponse(0, '上传文件读取失败');
}
$fileName = date('YmdHis') . uniqid('', true) . '.' . $ext;
$objectKey = $contactUserId > 0
? 'contact/' . $contactUserId . '/' . $fileName
: $fileName;
try {
$client = SwooleService::getInstance();
$sent = $client->sendTask([
'type' => 'upload_ali',
'data' => [
'Bucket' => BUCKET,
'Key' => $objectKey,
'file_content' => base64_encode($content),
],
]);
$client->close();
if (!$sent) {
return $this->uploadResponse(0, '上传失败,请重试');
}
$url = OSS_URL . $objectKey;
return $this->uploadResponse(1, '上传成功', [
'path' => $url,
'url' => $url,
]);
} catch (\Throwable $e) {
return $this->uploadResponse(0, '上传失败,请重试');
}
}
private function uploadResponse(int $code, string $msg, array $data = [])
{
return json([
'code' => $code,
'msg' => $msg,
'data' => $data,
], 200, [], ['json_encode_param' => 0]);
}
}