Preserve uploaded file extensions

This commit is contained in:
richjohnrambo
2026-09-07 16:13:20 +08:00
parent 35da3025a3
commit 8a9e202b56
8 changed files with 139 additions and 14 deletions
+70
View File
@@ -3,6 +3,8 @@ package media
import (
"strings"
"testing"
"github.com/tinode/chat/server/store/types"
)
func TestMatchCORSOrigin(t *testing.T) {
@@ -237,3 +239,71 @@ func TestExtensionByMimeType(t *testing.T) {
}
}
}
func TestMimeTypeForUploadPrefersContainerFilename(t *testing.T) {
cases := []struct {
name string
detect string
client string
filename string
want string
}{
{
name: "m4a misdetected as mp4",
detect: "video/mp4",
filename: "voice.m4a",
want: "audio/x-m4a",
},
{
name: "xlsx misdetected as zip",
detect: "application/zip",
filename: "iOS任务拆解.xlsx",
want: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
},
{
name: "client content type fallback",
detect: "application/octet-stream",
client: "image/jfif",
filename: "thumb",
want: "image/jfif",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := MimeTypeForUpload(tc.detect, tc.client, tc.filename); got != tc.want {
t.Fatalf("MimeTypeForUpload()=%q, want %q", got, tc.want)
}
})
}
}
func TestFileURLNamePrefersOriginalExtension(t *testing.T) {
cases := []struct {
name string
def *types.FileDef
want string
}{
{
name: "voice keeps m4a extension",
def: &types.FileDef{ObjHeader: types.ObjHeader{Id: "file123"}, MimeType: "video/mp4", OriginalName: "voice.m4a"},
want: "file123.m4a",
},
{
name: "xlsx keeps xlsx extension",
def: &types.FileDef{ObjHeader: types.ObjHeader{Id: "sheet123"}, MimeType: "application/zip", OriginalName: "iOS任务拆解.xlsx"},
want: "sheet123.xlsx",
},
{
name: "falls back to mime extension",
def: &types.FileDef{ObjHeader: types.ObjHeader{Id: "image123"}, MimeType: "image/jpeg"},
want: "image123.jpg",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := FileURLName(tc.def); got != tc.want {
t.Fatalf("FileURLName()=%q, want %q", got, tc.want)
}
})
}
}