forked from go-admin-team/go-admin-core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
129 lines (100 loc) · 2.13 KB
/
file.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
package utils
import (
"errors"
"io"
"log"
"mime/multipart"
"net/http"
"os"
"path"
"strings"
"github.com/shamsher31/goimgext"
)
// GetSize 获取文件大小
func GetSize(f multipart.File) (int, error) {
content, err := io.ReadAll(f)
return len(content), err
}
// GetExt 获取文件后缀
func GetExt(fileName string) string {
return path.Ext(fileName)
}
// CheckExist 检查文件是否存在
func CheckExist(src string) bool {
_, err := os.Stat(src)
return os.IsNotExist(err)
}
// CheckPermission 检查文件权限
func CheckPermission(src string) bool {
_, err := os.Stat(src)
return os.IsPermission(err)
}
// IsNotExistMkDir 检查文件夹是否存在
// 如果不存在则新建文件夹
func IsNotExistMkDir(src string) error {
if exist := !CheckExist(src); exist == false {
if err := MkDir(src); err != nil {
return err
}
}
return nil
}
// MkDir 新建文件夹
func MkDir(src string) error {
err := os.MkdirAll(src, os.ModePerm)
if err != nil {
return err
}
return nil
}
// Open 打开文件
func Open(name string, flag int, perm os.FileMode) (*os.File, error) {
f, err := os.OpenFile(name, flag, perm)
defer f.Close()
if err != nil {
return nil, err
}
return f, nil
}
// GetImgType 获取Img文件类型
func GetImgType(p string) (string, error) {
file, err := os.Open(p)
defer file.Close()
if err != nil {
log.Println(err)
os.Exit(1)
}
buff := make([]byte, 512)
_, err = file.Read(buff)
if err != nil {
log.Println(err)
os.Exit(1)
}
filetype := http.DetectContentType(buff)
ext := imgext.Get()
for i := 0; i < len(ext); i++ {
if strings.Contains(ext[i], filetype[6:len(filetype)]) {
return filetype, nil
}
}
return "", errors.New("Invalid image type")
}
// GetType 获取文件类型
func GetType(p string) (string, error) {
file, err := os.Open(p)
defer file.Close()
if err != nil {
log.Println(err)
os.Exit(1)
}
buff := make([]byte, 512)
_, err = file.Read(buff)
if err != nil {
log.Println(err)
}
filetype := http.DetectContentType(buff)
//ext := GetExt(p)
//var list = strings.Split(filetype, "/")
//filetype = list[0] + "/" + ext
return filetype, nil
}