-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
104 lines (81 loc) · 1.92 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
package upload
import (
"io"
"io/ioutil"
"mime/multipart"
"os"
"path"
"strings"
"github.com/spark8899/go-blog-service/global"
"github.com/spark8899/go-blog-service/pkg/util"
)
type FileType int
const TypeImage FileType = iota + 1
func GetFileName(name string) string {
ext := GetFileExt(name)
fileName := strings.TrimSuffix(name, ext)
fileName = util.EncodeMD5(fileName)
return fileName + ext
}
func GetFileExt(name string) string {
return path.Ext(name)
}
func GetSavePath() string {
return global.AppSetting.UploadSavePath
}
func GetServerUrl() string {
return global.AppSetting.UploadServerUrl
}
func CheckSavePath(dst string) bool {
_, err := os.Stat(dst)
return os.IsNotExist(err)
}
func CheckContainExt(t FileType, name string) bool {
ext := GetFileExt(name)
ext = strings.ToUpper(ext)
switch t {
case TypeImage:
for _, allowExt := range global.AppSetting.UploadImageAllowExts {
if strings.ToUpper(allowExt) == ext {
return true
}
}
}
return false
}
func CheckMaxSize(t FileType, f multipart.File) bool {
content, _ := ioutil.ReadAll(f)
size := len(content)
switch t {
case TypeImage:
if size >= global.AppSetting.UploadImageMaxSize*1024*1024 {
return true
}
}
return false
}
func CheckPermission(dst string) bool {
_, err := os.Stat(dst)
return os.IsPermission(err)
}
func CreateSavePath(dst string, perm os.FileMode) error {
err := os.MkdirAll(dst, perm)
if err != nil {
return err
}
return nil
}
func SaveFile(file *multipart.FileHeader, dst string) error {
src, err := file.Open()
if err != nil {
return err
}
defer src.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, src)
return err
}