From 9cc82df980b85f6e32eaade4f1adc49e79e73f0b Mon Sep 17 00:00:00 2001 From: nepiedg <806669289@qq.com.com> Date: Mon, 20 Apr 2026 02:06:36 +0000 Subject: [PATCH] feat(note): improve audio MIME type detection during upload - Replaced direct MIME type retrieval with a new method `detectAudioMimeType` to enhance stability in environments without fileinfo support. - The new method prioritizes file extensions and falls back to the original file name if necessary, ensuring reliable MIME type detection for audio files. --- app/note/service/NoteService.php | 37 +++++++++++++++++++++++++++++++- 1 file changed, 36 insertions(+), 1 deletion(-) diff --git a/app/note/service/NoteService.php b/app/note/service/NoteService.php index 1731d6b..e2e1229 100644 --- a/app/note/service/NoteService.php +++ b/app/note/service/NoteService.php @@ -249,7 +249,11 @@ class NoteService $audio->file_path = $savedPath; $audio->file_url = $this->buildPublicFileUrl($savedPath); $audio->file_size = (int) $file->getSize(); - $audio->mime_type = (string) $file->getMime(); + /** + * 线上环境若未启用 fileinfo/finfo,ThinkPHP 的 getMime() 会直接抛错。 + * 这里改为按文件扩展名做稳定兜底,避免“文件已写入磁盘但接口因取 mime 失败而整体报错”。 + */ + $audio->mime_type = $this->detectAudioMimeType($savedPath, $file); $audio->duration_ms = max(0, $durationMs); $audio->updated_at = $now; $audio->save(); @@ -409,6 +413,37 @@ class NoteService ]; } + /** + * 推断音频 MIME。 + * + * 优先使用文件扩展名,避免依赖 fileinfo 扩展;若扩展名缺失,再尝试读取客户端原始文件名。 + * + * @param string $savedPath + * @param File $file + * @return string + */ + private function detectAudioMimeType(string $savedPath, File $file): string + { + $extension = strtolower((string) pathinfo($savedPath, PATHINFO_EXTENSION)); + if ($extension === '') { + $extension = strtolower((string) pathinfo((string) $file->getOriginalName(), PATHINFO_EXTENSION)); + } + + $mimeMap = [ + 'aac' => 'audio/aac', + 'amr' => 'audio/amr', + 'm4a' => 'audio/mp4', + 'mp3' => 'audio/mpeg', + 'mp4' => 'audio/mp4', + 'ogg' => 'audio/ogg', + 'pcm' => 'audio/L16', + 'wav' => 'audio/wav', + 'webm' => 'audio/webm', + ]; + + return $mimeMap[$extension] ?? 'application/octet-stream'; + } + /** * 规范化标题 *