Skip to content

Commit

Permalink
feat: 添加文件体积验证
Browse files Browse the repository at this point in the history
  • Loading branch information
RockChinQ committed Oct 20, 2024
1 parent dee2ac6 commit 1aa9ed4
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 2 deletions.
2 changes: 2 additions & 0 deletions backend/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ func SetInitValue() {
viper.SetDefault("backend.host", "0.0.0.0")
viper.SetDefault("backend.port", "8081")

viper.SetDefault("feature.image_max_size", 1024*1024*2)

// jwt
viper.SetDefault("auth.jwt.secret", uuid.New().String())
viper.SetDefault("auth.jwt.expire", 3600*6)
Expand Down
18 changes: 16 additions & 2 deletions backend/controller/postapi.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ package controller

import (
"bytes"
"fmt"
"strconv"

"github.com/RockChinQ/Campux/backend/database"
"github.com/RockChinQ/Campux/backend/service"
"github.com/RockChinQ/Campux/backend/util"
"github.com/gin-gonic/gin"
"github.com/spf13/viper"
)

type PostRouter struct {
Expand Down Expand Up @@ -51,16 +53,28 @@ func (pr *PostRouter) UploadImage(c *gin.Context) {
}

// 取body的json里的图片数据
file, _, err := c.Request.FormFile("image")
file, err := c.FormFile("image")
if err != nil {
pr.Fail(c, 1, err.Error())
return
}
// 检查图片大小
if file.Size > int64(viper.GetInt("feature.image_max_size")) {
pr.Fail(c, 1, fmt.Sprintf("图片文件过大 (%.2f MB > %.2f MB)", float64(file.Size)/1024/1024, float64(viper.GetInt("feature.image_max_size"))/1024/1024))
return
}

suffix := c.Request.FormValue("suffix")

fileReader, err := file.Open()

if err != nil {
pr.Fail(c, 1, err.Error())
return
}

// 上传图片
key, err := pr.PostService.UploadImage(file, suffix)
key, err := pr.PostService.UploadImage(fileReader, suffix)

if err != nil {
pr.Fail(c, 1, err.Error())
Expand Down
1 change: 1 addition & 0 deletions backend/migrate/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
var migrations = []Migration{
&ms.LocalStorageConfig{},
&ms.SQLiteConfig{},
&ms.ImageMaxSize{},
}

// Migration interface
Expand Down
22 changes: 22 additions & 0 deletions backend/migrate/migrations/image_max_size.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package migrations

import (
"github.com/RockChinQ/Campux/backend/config"
"github.com/spf13/viper"
)

type ImageMaxSize struct{}

func (i *ImageMaxSize) Name() string {
return "ImageMaxSize"
}

func (i *ImageMaxSize) Check() bool {
return !viper.IsSet("feature.image_max_size")
}

func (i *ImageMaxSize) Up() error {
viper.Set("feature.image_max_size", 1024*1024*2)

return config.WriteConfig()
}

0 comments on commit 1aa9ed4

Please sign in to comment.