This commit is contained in:
2026-05-12 13:45:08 +08:00
parent e81df5ce5a
commit 37d3461983
38 changed files with 1721 additions and 1113 deletions

View File

@@ -11,6 +11,10 @@ func DetectFileType(data []byte) (contentType string, ext string) {
return "application/octet-stream", ""
}
ct := http.DetectContentType(data)
// http.DetectContentType 可能带 charset 等参数text/plain; charset=utf-8
if idx := strings.Index(ct, ";"); idx > 0 {
ct = strings.TrimSpace(ct[:idx])
}
switch ct {
case "audio/mpeg":
return ct, ".mp3"
@@ -24,12 +28,20 @@ func DetectFileType(data []byte) (contentType string, ext string) {
return ct, ".jpg"
case "application/pdf":
return ct, ".pdf"
case "text/plain":
return ct, ".txt"
case "application/json":
return ct, ".json"
default:
// 兜底:尝试从 ct 截取 subtype 作为后缀(例如 application/json
if parts := strings.Split(ct, "/"); len(parts) == 2 {
return ct, "." + parts[1]
sub := parts[1]
// 避免出现 "plain; charset=utf-8" 之类的后缀
if idx := strings.Index(sub, ";"); idx > 0 {
sub = strings.TrimSpace(sub[:idx])
}
return ct, "." + sub
}
return ct, ""
}
}