Browse Source

修复图片格式验证

kobe6258 3 months ago
parent
commit
a104a0123b
5 changed files with 37 additions and 0 deletions
  1. 5 0
      controllers/analyst.go
  2. 5 0
      controllers/image.go
  3. 5 0
      controllers/product.go
  4. 5 0
      controllers/video.go
  5. 17 0
      utils/imageUtils.go

+ 5 - 0
controllers/analyst.go

@@ -41,6 +41,11 @@ func (this *AnalystController) UploadImage() {
 		br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
 		return
 	}
+	if !utils.CheckImageFormat(h.Filename, f, h) {
+		br.Msg = "图片上传失败"
+		br.ErrMsg = "图片上传失败,不支持的文件格式"
+		return
+	}
 	defer f.Close()
 	ext := path.Ext(h.Filename)
 	size, err := strconv.Atoi(utils.UPLOAD_IMG_SIZE)

+ 5 - 0
controllers/image.go

@@ -37,6 +37,11 @@ func (this *ImageController) UploadImage() {
 		br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
 		return
 	}
+	if !utils.CheckImageFormat(h.Filename, f, h) {
+		br.Msg = "图片上传失败"
+		br.ErrMsg = "图片上传失败,不支持的文件格式"
+		return
+	}
 	defer f.Close()
 	size, err := strconv.Atoi(utils.UPLOAD_IMG_SIZE)
 	if err != nil {

+ 5 - 0
controllers/product.go

@@ -714,6 +714,11 @@ func (this *ProductController) UploadFile() {
 		br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
 		return
 	}
+	if !utils.CheckImageFormat(h.Filename, f, h) {
+		br.Msg = "图片上传失败"
+		br.ErrMsg = "图片上传失败,不支持的文件格式"
+		return
+	}
 	defer f.Close()
 	size, err := strconv.Atoi(utils.UPLOAD_IMG_SIZE)
 	if err != nil {

+ 5 - 0
controllers/video.go

@@ -492,6 +492,11 @@ func (this *VideoController) UploadFile() {
 		br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
 		return
 	}
+	if !utils.CheckImageFormat(h.Filename, f, h) {
+		br.Msg = "图片上传失败"
+		br.ErrMsg = "图片上传失败,不支持的文件格式"
+		return
+	}
 	defer f.Close()
 	size, err := strconv.Atoi(utils.UPLOAD_IMG_SIZE)
 	if err != nil {

+ 17 - 0
utils/imageUtils.go

@@ -5,11 +5,28 @@ import (
 	"image"
 	"image/png"
 	"log"
+	"mime/multipart"
 	"os"
 	"path/filepath"
 	"strings"
 )
 
+var (
+	imgExtMap = map[string]string{
+		".jpg":  "image/jpeg",
+		".jpeg": "image/jpeg",
+		".png":  "image/png",
+	}
+)
+
+func CheckImageFormat(fileName string, file multipart.File, header *multipart.FileHeader) bool {
+	ext := strings.ToLower(filepath.Ext(fileName))
+	contentType := header.Header.Get("Content-Type")
+	if imgExtMap[ext] == contentType {
+		return true
+	}
+	return false
+}
 func ImageResize(imageSrc string, maxDimension int) (string, error) {
 	file, err := os.Open(imageSrc)
 	if err != nil {