|
|
package controllers
|
|
|
|
|
|
import (
|
|
|
"fmt"
|
|
|
"io"
|
|
|
"mime/multipart"
|
|
|
"oppmg/common/config"
|
|
|
"oppmg/common/log"
|
|
|
"oppmg/protocol"
|
|
|
"oppmg/utils"
|
|
|
"os"
|
|
|
"path"
|
|
|
"path/filepath"
|
|
|
"time"
|
|
|
)
|
|
|
|
|
|
//UploadController 文件上传
|
...
|
...
|
@@ -13,6 +19,10 @@ type UploadController struct { |
|
|
BaseController
|
|
|
}
|
|
|
|
|
|
type ResponseUploadImage struct {
|
|
|
Urls []string `json:"url"`
|
|
|
}
|
|
|
|
|
|
//UploadImage 图片上传
|
|
|
//@router /image
|
|
|
func (c *UploadController) UploadImage() {
|
...
|
...
|
@@ -24,35 +34,42 @@ func (c *UploadController) UploadImage() { |
|
|
if err != nil {
|
|
|
log.Error("获取上传文件失败:%s", err)
|
|
|
}
|
|
|
var rsp ResponseUploadImage
|
|
|
for i := range filehead {
|
|
|
err := saveFile(filehead[i], "")
|
|
|
hostpath, err := saveFile(filehead[i], "image")
|
|
|
if err != nil {
|
|
|
msg = protocol.BadRequestParam("1")
|
|
|
return
|
|
|
}
|
|
|
rsp.Urls = append(rsp.Urls, hostpath)
|
|
|
}
|
|
|
msg = protocol.NewReturnResponse(nil, nil)
|
|
|
msg = protocol.NewReturnResponse(rsp, nil)
|
|
|
return
|
|
|
}
|
|
|
|
|
|
func saveFile(fileData *multipart.FileHeader, src string) error {
|
|
|
os.MkdirAll("./file/opp", 0777)
|
|
|
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
|
|
|
return "", err
|
|
|
}
|
|
|
dst, err := os.Create("./file/opp/" + fileData.Filename)
|
|
|
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
|
|
|
return "", err
|
|
|
}
|
|
|
if _, err := io.Copy(dst, file); err != nil {
|
|
|
log.Error("文件保存失败:%s", err)
|
|
|
return err
|
|
|
return "", err
|
|
|
}
|
|
|
return nil
|
|
|
hostpath = config.MConfig.FileHost + filepath.Join(config.MConfig.FileHostPath, fileType, mfileName)
|
|
|
return hostpath, nil
|
|
|
} |
...
|
...
|
|