You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
69 lines
1.4 KiB
69 lines
1.4 KiB
package photo
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"github.com/gin-gonic/gin"
|
|
"path/filepath"
|
|
"recook/internal/back"
|
|
"recook/internal/static_path"
|
|
"recook/tools"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
MaxPhotoFileMemory = 3 << 20 // 1MB
|
|
)
|
|
|
|
func UploadPhoto(c *gin.Context) {
|
|
f, err := c.FormFile("photo")
|
|
if err != nil {
|
|
back.Fail(c, err.Error())
|
|
return
|
|
}
|
|
|
|
if f.Size > MaxPhotoFileMemory {
|
|
back.Fail(c, "文件太大")
|
|
return
|
|
}
|
|
|
|
name, err := generatePhotoFilename(f.Filename)
|
|
if err != nil {
|
|
back.Fail(c, err.Error())
|
|
return
|
|
}
|
|
|
|
path := filepath.Join(static_path.Dir.Photo, name)
|
|
uri := filepath.Join(static_path.Dir.Root, path)
|
|
|
|
err = c.SaveUploadedFile(f, uri)
|
|
if err != nil {
|
|
back.Err(c, err.Error())
|
|
return
|
|
}
|
|
|
|
back.Suc(c, "上传成功", gin.H{
|
|
"url": path,
|
|
})
|
|
}
|
|
|
|
// ===================================================
|
|
// ============== 私有 生成文件名称 =============
|
|
// ===================================================
|
|
func generatePhotoFilename(fn string) (name string, err error) {
|
|
n := filepath.Base(fn)
|
|
|
|
elements := strings.Split(n, ".")
|
|
en := elements[len(elements)-1:][0]
|
|
en = strings.ToLower(en)
|
|
|
|
if en != "png" && en != "jpg" && en != "jpeg" && en != "gif" {
|
|
err := errors.New("图片类型不支持")
|
|
return "", err
|
|
}
|
|
|
|
hash := tools.MD5(fmt.Sprintf("%d", time.Now().UnixNano()/1000))
|
|
return fmt.Sprintf("%v.%v", hash, en), nil
|
|
}
|