upload.go
1.1 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
package controllers
import (
"io"
"mime/multipart"
"oppmg/common/log"
"oppmg/protocol"
"os"
)
//UploadController 文件上传
type UploadController struct {
BaseController
}
//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)
}
for i := range filehead {
err := saveFile(filehead[i], "")
if err != nil {
msg = protocol.BadRequestParam("1")
return
}
}
msg = protocol.NewReturnResponse(nil, nil)
return
}
func saveFile(fileData *multipart.FileHeader, src string) error {
os.MkdirAll("./file/opp", 0777)
file, err := fileData.Open()
defer file.Close()
if err != nil {
log.Error("文件获取失败%s", err)
return err
}
dst, err := os.Create("./file/opp/" + fileData.Filename)
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
}
return nil
}