76 lines
1.7 KiB
Go
76 lines
1.7 KiB
Go
package constants
|
||
|
||
import (
|
||
"github.com/gabriel-vasile/mimetype"
|
||
"io"
|
||
"strings"
|
||
)
|
||
|
||
type FileType string
|
||
|
||
const (
|
||
FileTypeUnknown FileType = "unknown"
|
||
FileTypeImage FileType = "image"
|
||
//FileTypeVideo FileType = "video"
|
||
FileTypeExcel FileType = "excel"
|
||
FileTypeWord FileType = "word"
|
||
FileTypeTxt FileType = "txt"
|
||
FileTypePDF FileType = "pdf"
|
||
)
|
||
|
||
var FileTypeMappings = map[FileType][]string{
|
||
FileTypeImage: {
|
||
"image/jpeg", "image/png", "image/gif", "image/webp", "image/svg+xml",
|
||
".jpg", ".jpeg", ".png", ".gif", ".webp", ".svg",
|
||
},
|
||
FileTypeExcel: {
|
||
"application/vnd.ms-excel",
|
||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||
".xls", ".xlsx",
|
||
},
|
||
FileTypeWord: {
|
||
"application/msword",
|
||
"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
|
||
".doc", ".docx",
|
||
},
|
||
FileTypePDF: {
|
||
"application/pdf",
|
||
".pdf",
|
||
},
|
||
FileTypeTxt: {
|
||
"text/plain",
|
||
".txt",
|
||
},
|
||
}
|
||
|
||
func DetectFileType(file io.ReadSeeker) (FileType, error) {
|
||
// 读取文件头(512字节足够检测大多数类型)
|
||
buffer := make([]byte, 512)
|
||
n, err := file.Read(buffer)
|
||
if err != nil && err != io.EOF {
|
||
return FileTypeUnknown, err
|
||
}
|
||
|
||
// 重置读取位置
|
||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||
return FileTypeUnknown, err
|
||
}
|
||
|
||
// 检测 MIME 类型
|
||
detectedMIME := mimetype.Detect(buffer[:n]).String()
|
||
|
||
// 遍历映射表,匹配 MIME 或扩展名
|
||
for fileType, mimesOrExts := range FileTypeMappings {
|
||
for _, item := range mimesOrExts {
|
||
if strings.HasPrefix(item, ".") {
|
||
continue // 跳过扩展名(仅 MIME 检测)
|
||
}
|
||
if item == detectedMIME {
|
||
return fileType, nil
|
||
}
|
||
}
|
||
}
|
||
|
||
return FileTypeUnknown, nil
|
||
}
|