Created
September 1, 2020 07:25
-
-
Save codcodog/c057318233e9222c49b05f0492b420a6 to your computer and use it in GitHub Desktop.
上传图片校验
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"image" | |
_ "image/gif" | |
_ "image/jpeg" | |
_ "image/png" | |
) | |
// 注意,需要 import 图片格式的包,要不 decodeConfig 会报 image: unknown format | |
func uploadOpcategoryImage(c *bm.Context) { | |
websiteID := middlewares.GetCurrentWebsiteID(c) | |
if websiteID == 0 { | |
c.JSON(nil, apicode.ErrNullWebsite) | |
return | |
} | |
file, header, err := c.Request.FormFile("file") | |
if err != nil { | |
c.JSON(nil, ecode.Error(ecode.RequestErr, err.Error())) | |
return | |
} | |
defer file.Close() | |
// 校验尺寸大小 | |
image, _, err := image.DecodeConfig(file) | |
if err != nil { | |
c.JSON(nil, ecode.Error(ecode.RequestErr, err.Error())) | |
return | |
} | |
if image.Width != 128 || image.Height != 128 { | |
c.JSON(nil, ecode.Error(ecode.RequestErr, "图片尺寸只支持128px*128px")) | |
return | |
} | |
ext := filepath.Ext(header.Filename) | |
validExt := []string{".jpg", ".jpeg", ".png", ".gif"} | |
if !contains.StringsInSlice(validExt, ext) { | |
c.JSON(nil, ecode.Error(ecode.RequestErr, "图片格式只支持 jpg, png, gif 格式")) | |
return | |
} | |
if header.Size > int64(storage.UPLOAD_OPCATEGORY_IMAGE) { | |
c.JSON(nil, ecode.Error(ecode.RequestErr, "文件大小不能超过100k")) | |
return | |
} | |
fileId, src, err := storage.UploadImage(websiteID, header.Filename, file, true) | |
if err != nil { | |
c.JSON(nil, ecode.Error(ecode.RequestErr, err.Error())) | |
return | |
} | |
resp := map[string]interface{}{ | |
"file_id": fileId, | |
"src": src, | |
} | |
c.JSON(resp, nil) | |
return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment