You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

93 lines
2.8 KiB

3 days ago
<?php
namespace App\Http\Controllers\Api;
3 days ago
use App\Http\Controllers\Concerns\EnsuresPublicDiskWritable;
3 days ago
use App\Http\Controllers\Concerns\StoresPublicUploadWithoutFileinfo;
3 days ago
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
3 days ago
use Illuminate\Support\Facades\Log;
3 days ago
use Throwable;
3 days ago
class UploadController extends Controller
{
3 days ago
use EnsuresPublicDiskWritable;
3 days ago
use StoresPublicUploadWithoutFileinfo;
3 days ago
3 days ago
public function store(Request $request): JsonResponse
{
3 days ago
if ($early = $this->ensurePublicDiskReady()) {
return $early;
}
3 days ago
if (!$request->hasFile('file')) {
return response()->json([
'message' => '未收到文件,请使用 multipart 表单字段名 file。',
], 422);
}
$uploaded = $request->file('file');
if (!$uploaded->isValid()) {
return response()->json([
'message' => '上传未通过校验:'.$uploaded->getErrorMessage(),
], 422);
}
3 days ago
$data = $request->validate([
'file' => ['required', 'file', 'max:20480'],
]);
3 days ago
try {
3 days ago
$path = $this->storeUploadedFileAsUniqueName($data['file'], 'uploads');
3 days ago
} catch (Throwable $e) {
report($e);
3 days ago
Log::error('upload_putfile_failed', [
'message' => $e->getMessage(),
'public_path' => storage_path('app/public'),
]);
3 days ago
return response()->json([
'message' => '文件保存失败',
3 days ago
'detail' => config('app.debug') ? $e->getMessage() : null,
3 days ago
], 500);
}
if ($path === false) {
3 days ago
Log::error('upload_putfile_returned_false', [
'public_path' => storage_path('app/public'),
]);
3 days ago
return response()->json([
3 days ago
'message' => '文件保存失败(写入返回失败)',
'detail' => config('app.debug') ? 'Storage::putFile 返回 false多为磁盘 public 配置或权限问题' : null,
3 days ago
], 500);
}
3 days ago
$mime = self::jsonSafeString($this->mimeForUploadResponse($data['file']));
3 days ago
3 days ago
return response()->json([
'path' => $path,
3 days ago
'url' => url('/storage/'.str_replace('\\', '/', $path)),
3 days ago
'mime' => $mime,
3 days ago
'size' => $data['file']->getSize(),
]);
}
3 days ago
/** 避免 mime 等字段含非法 UTF-8 导致 json_encode 抛错成 500 */
private static function jsonSafeString(string $value): string
{
if ($value === '') {
return '';
}
if (function_exists('mb_scrub')) {
return mb_scrub($value, 'UTF-8');
}
$clean = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
return $clean !== false ? $clean : 'application/octet-stream';
}
3 days ago
}