package controllers
|
|
import (
|
"bytes"
|
"github.com/gin-gonic/gin"
|
"io"
|
"path"
|
"strings"
|
"wms/constvar"
|
"wms/extend/code"
|
"wms/extend/util"
|
"wms/models"
|
"wms/pkg/logx"
|
"wms/utils/image"
|
"wms/utils/upload"
|
)
|
|
type AttachmentController struct {
|
}
|
|
// UploadFiles
|
//
|
// @Tags 附件管理
|
// @Summary 上传附件
|
// @Success 200 {object} util.Response "成功"
|
// @Router /api-wms/v1/attachment/uploadFiles [post]
|
func (slf AttachmentController) UploadFiles(c *gin.Context) {
|
form, err := c.MultipartForm()
|
if err != nil {
|
logx.Errorf("file upload err: %v", err)
|
util.ResponseFormat(c, code.RequestParamError, "参数解析失败")
|
return
|
}
|
files := form.File["files"]
|
|
var attachmentList []*models.Attachment
|
for _, fileHeader := range files {
|
ext := strings.ToLower(path.Ext(fileHeader.Filename))[1:]
|
fileParams := strings.Split(fileHeader.Filename, ".")
|
var fileType constvar.FileType
|
if value, ok := constvar.FileExtMap[ext]; ok {
|
fileType = value
|
}
|
if value, ok := constvar.PicExtMap[ext]; ok {
|
fileType = value
|
}
|
if fileType == "" {
|
logx.Errorf("file upload err: 不支持上传该格式的文件")
|
util.ResponseFormat(c, code.RequestParamError, "不支持上传该格式的文件")
|
return
|
}
|
file, err := fileHeader.Open()
|
if err != nil {
|
logx.Errorf("file upload err: %v", err)
|
util.ResponseFormat(c, code.RequestParamError, "错误文件")
|
return
|
}
|
buffer := new(bytes.Buffer)
|
_, _ = io.Copy(buffer, file)
|
fileBytes := buffer.Bytes()
|
fileUrl, err := upload.UploadFileToSeaWeed(string(fileType), fileHeader.Filename, fileBytes)
|
if err != nil {
|
logx.Errorf("file upload err: %v", err)
|
util.ResponseFormat(c, code.RequestParamError, err.Error())
|
return
|
}
|
|
attachment := &models.Attachment{
|
FileName: fileHeader.Filename,
|
FileUrl: fileUrl,
|
Ext: ext,
|
FileType: fileType,
|
}
|
attachmentList = append(attachmentList, attachment)
|
|
if fileType == constvar.FileType_Picture {
|
thumbnailBytes, err := image.CreateThumbnail(fileBytes, 60, 0, 0)
|
if err != nil {
|
logx.Errorf("file upload err: %v", err)
|
util.ResponseFormat(c, code.RequestParamError, "生成缩略图失败:"+err.Error())
|
return
|
}
|
thumbnailUrl, err := upload.UploadFileToSeaWeed(string(constvar.FileType_Thumbnail), fileParams[0]+"thumbnail."+ext, thumbnailBytes)
|
if err != nil {
|
logx.Errorf("file upload err: %v", err)
|
util.ResponseFormat(c, code.RequestParamError, err.Error())
|
return
|
}
|
|
thumbAttach := &models.Attachment{
|
FileName: fileHeader.Filename,
|
FileUrl: thumbnailUrl,
|
Ext: ext,
|
FileType: constvar.FileType_Thumbnail,
|
}
|
attachmentList = append(attachmentList, thumbAttach)
|
}
|
}
|
|
if len(attachmentList) > 0 {
|
if attachmentList, err = models.NewAttachmentSearch().CreateBatchWithResp(attachmentList); err != nil {
|
logx.Errorf("attachment create err: %v", err)
|
util.ResponseFormat(c, code.SaveFail, "文件保存失败")
|
return
|
}
|
}
|
|
util.ResponseFormat(c, code.Success, attachmentList)
|
}
|