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
+52
View File
@@ -69,6 +69,58 @@ type AllowedOrigin struct {
var fileNamePattern = regexp.MustCompile(`^[-_A-Za-z0-9]+`)
var uploadExtensionMimeTypes = map[string]string{
".aac": "audio/aac",
".m4a": "audio/x-m4a",
".doc": "application/msword",
".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
".ppt": "application/vnd.ms-powerpoint",
".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation",
".xls": "application/vnd.ms-excel",
".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
}
// MimeTypeForUpload picks the MIME type to persist for an uploaded file. Some common formats are
// containers and are misdetected by http.DetectContentType, for example m4a as video/mp4 and Office
// documents as zip, so the original file extension wins for those cases.
func MimeTypeForUpload(detected, clientContentType, originalName string) string {
ext := ExtensionByFilename(originalName)
if extMime := uploadExtensionMimeTypes[ext]; extMime != "" {
return extMime
}
if clientContentType != "" {
return clientContentType
}
return strings.TrimSpace(detected)
}
// FileURLName returns the public URL file name for a stored file.
func FileURLName(fdef *types.FileDef) string {
if fdef == nil {
return ""
}
fname := fdef.Id
if ext := ExtensionByFilename(fdef.OriginalName); ext != "" {
return fname + ext
}
return fname + ExtensionByMimeType(fdef.MimeType)
}
// ExtensionByFilename returns a safe lower-case extension from a client-provided file name.
func ExtensionByFilename(name string) string {
_, fname := path.Split(strings.TrimSpace(name))
ext := strings.ToLower(path.Ext(fname))
if len(ext) < 2 || len(ext) > 16 {
return ""
}
for _, r := range ext[1:] {
if (r < 'a' || r > 'z') && (r < '0' || r > '9') {
return ""
}
}
return ext
}
// ExtensionByMimeType returns a stable URL extension for uploaded media.
func ExtensionByMimeType(mimeType string) string {
switch strings.ToLower(strings.TrimSpace(strings.Split(mimeType, ";")[0])) {