/
server_upload.go
52 lines (41 loc) · 1.2 KB
/
server_upload.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
package goo
import (
"fmt"
"github.com/gin-gonic/gin"
goo_utils "github.com/liqiongtao/googo.io/goo-utils"
"io/ioutil"
"os"
"path"
)
type LocalUpload struct {
}
func (lu LocalUpload) Upload(c *gin.Context, uploadDir string) *Response {
f, fh, err := c.Request.FormFile("file")
if err != nil {
return Error(7001, fmt.Sprintf("上传失败,原因:%s", err.Error()))
}
data, err := ioutil.ReadAll(f)
if err != nil {
return Error(7002, fmt.Sprintf("上传失败,原因:%s", err.Error()))
}
f.Close()
md5str := goo_utils.MD5(data)
filepath := md5str[0:2] + "/" + md5str[2:4] + "/"
if err := os.MkdirAll(uploadDir+filepath, 0755); err != nil {
return Error(7003, fmt.Sprintf("上传失败,原因:%s", err.Error()))
}
fileExt := path.Ext(fh.Filename)
fileBasename := path.Base(fh.Filename)
filename := filepath + fileBasename + "_" + md5str[8:16] + fileExt
ff, err := os.Create(uploadDir + filename)
if err != nil {
return Error(7004, fmt.Sprintf("上传失败,原因:%s", err.Error()))
}
defer ff.Close()
if _, err := ff.Write(data); err != nil {
return Error(7005, fmt.Sprintf("上传失败,原因:%s", err.Error()))
}
return Success(gin.H{
"url": filename,
})
}