upload.go 2.4 KB
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)
	err = os.MkdirAll(savepath, 0777)
	if err != nil {
		log.Error("目录创建失败:%s", err)
		return "", err
	}
	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)
	log.Debug("文件保存地址%s", filepath.Join(savepath, mfileName))
	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
}

//UploadVideo 视频上传
//@router /video
func (c *UploadController) UploadVideo() {
	var msg *protocol.ResponseMessage
	defer func() {
		c.ResposeJson(msg)
	}()
	filehead, err := c.GetFiles("file")
	if err != nil {
		log.Error("获取上传文件失败:%s", err)
		return
	}
	var rsp ResponseUploadImage
	for i := range filehead {
		hostpath, err := saveFile(filehead[i], "video")
		if err != nil {
			msg = protocol.BadRequestParam("1")
			return
		}
		rsp.Urls = append(rsp.Urls, hostpath)
	}
	msg = protocol.NewReturnResponse(rsp, nil)
	return
}