upload.go
1.7 KB
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
package controllers
import (
"fmt"
"io"
"mime/multipart"
"oppmg/common/config"
"oppmg/common/log"
"oppmg/protocol"
"oppmg/utils"
"os"
"path"
"path/filepath"
"time"
)
//UploadController 文件上传
type UploadController struct {
BaseController
}
type ResponseUploadImage struct {
Urls []string `json:"url"`
}
//UploadImage 图片上传
//@router /image
func (c *UploadController) UploadImage() {
var msg *protocol.ResponseMessage
defer func() {
c.ResposeJson(msg)
}()
filehead, err := c.GetFiles("file")
if err != nil {
log.Error("获取上传文件失败:%s", err)
}
var rsp ResponseUploadImage
for i := range filehead {
hostpath, err := saveFile(filehead[i], "image")
if err != nil {
msg = protocol.BadRequestParam("1")
return
}
rsp.Urls = append(rsp.Urls, hostpath)
}
msg = protocol.NewReturnResponse(rsp, nil)
return
}
func saveFile(fileData *multipart.FileHeader, fileType string) (hostpath string, err error) {
savepath := filepath.Join(config.MConfig.FileSavePath, fileType)
os.MkdirAll(savepath, 0777)
file, err := fileData.Open()
defer file.Close()
if err != nil {
log.Error("文件获取失败%s", err)
return "", err
}
subfix := path.Ext(fileData.Filename)
mfileName := fmt.Sprint(utils.GenerateIDBySonyflake())
mfileName = fmt.Sprintf("%d_%s%s", time.Now().Unix(), mfileName, subfix)
dst, err := os.Create(filepath.Join(savepath, mfileName))
defer dst.Close()
if err != nil {
log.Error("目录访问失败:%s", err)
return "", err
}
if _, err := io.Copy(dst, file); err != nil {
log.Error("文件保存失败:%s", err)
return "", err
}
hostpath = config.MConfig.FileHost + filepath.Join(config.MConfig.FileHostPath, fileType, mfileName)
return hostpath, nil
}