瀏覽代碼

base64编码转成图片存储到本地

huangyan 1 年之前
父節點
當前提交
6b91a07bea
共有 4 個文件被更改,包括 62 次插入151 次删除
  1. 36 145
      app/controller/file.go
  2. 8 5
      app/model/model.go
  3. 1 1
      main.go
  4. 17 0
      utils/base64image.go

+ 36 - 145
app/controller/file.go

@@ -2,14 +2,20 @@ package controller
 
 import (
 	"context"
+	"encoding/base64"
 	"file_upload/app/e"
+	"file_upload/app/model"
 	"file_upload/global"
 	"file_upload/simple_zap"
+	"file_upload/utils"
+	"fmt"
 	"github.com/gin-gonic/gin"
 	"github.com/go-playground/validator/v10"
 	"go.mongodb.org/mongo-driver/bson"
 	"go.mongodb.org/mongo-driver/mongo/options"
 	"go.uber.org/zap"
+	"os"
+	"path/filepath"
 )
 
 type Body struct {
@@ -18,45 +24,13 @@ type Body struct {
 	Type bool
 }
 
-//func SaveFile(c *gin.Context) {
-//	file := Body{}
-//	err := c.BindJSON(&file)
-//	if err != nil {
-//		simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取参数失败")
-//		e.ResponseWithMsg(c, e.JSONParsingFailed, e.JSONParsingFailed.GetMsg())
-//		return
-//	}
-//	m := map[string]any{
-//		"type": file.Type,
-//		"data": file.Data,
-//	}
-//	marshal, err := sonic.Marshal(m)
-//	if err != nil {
-//		simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "序列化失败")
-//		e.ResponseWithMsg(c, e.ERROR, e.ERROR.GetMsg())
-//		return
-//	}
-//	result, err := global.Rdb.Exists(context.Background(), file.Name).Result()
-//	if result == 1 {
-//		e.ResponseWithMsg(c, e.AlreadyExists, e.AlreadyExists.GetMsg())
-//		return
-//	}
-//	set := global.Rdb.Set(context.Background(), file.Name, marshal, 0)
-//	if set.Err() != nil {
-//		simple_zap.WithCtx(context.Background()).Sugar().Warn(set.Err(), "保存文件失败")
-//		e.ResponseWithMsg(c, e.ERROR, e.ERROR.GetMsg())
-//		return
-//	}
-//	e.ResponseSuccess(c, e.SUCCESS)
-//}
-
 // SaveFile 保存文件到MongoDB
 // 参数:
 // - c *gin.Context: Gin框架的上下文对象,用于处理HTTP请求和响应
 // 无返回值
 func SaveFile(c *gin.Context) {
 	// 解析请求体中的文件信息
-	file := Body{}
+	file := model.Root{}
 	err := c.BindJSON(&file)
 	if err != nil {
 		// 日志记录参数解析失败
@@ -71,6 +45,35 @@ func SaveFile(c *gin.Context) {
 		"type": file.Type,
 		"data": file.Data,
 	}
+	if len(file.Data.Elements) == 2 {
+		imagCode := file.Data.Elements[1].Url
+		_, data := utils.ParseBase64ImageString(imagCode)
+		decodeString, err := base64.StdEncoding.DecodeString(data)
+		if err != nil {
+			simple_zap.WithCtx(context.TODO()).Sugar().Warn(err, "base64解码失败")
+			e.ResponseWithMsg(c, e.ERROR, "图片转换失败")
+			return
+		}
+		optputpath := "./upload" + "/" + file.Name + ".png"
+		create, err := os.Create(optputpath)
+		if err != nil {
+			simple_zap.WithCtx(context.TODO()).Sugar().Warn(err, "创建文件失败")
+			e.ResponseWithMsg(c, e.ERROR, "创建文件失败")
+		}
+		defer create.Close()
+		_, err = create.Write(decodeString)
+		if err != nil {
+			simple_zap.WithCtx(context.TODO()).Sugar().Warn(err, "写入文件失败")
+			e.ResponseWithMsg(c, e.ERROR, "写入文件失败")
+		}
+		simple_zap.WithCtx(context.TODO()).Sugar().Info("文件写入成功")
+		abs, err := filepath.Abs(optputpath)
+		if err != nil {
+			simple_zap.WithCtx(context.TODO()).Sugar().Warn()
+		}
+		file.Data.Elements[1].Url = abs
+		fmt.Println(file.Data.Elements[1].Url)
+	}
 	// 检查文件是否已存在
 	filter := bson.M{"name": file.Name}
 	count, err := global.MongoCon.CountDocuments(context.TODO(), filter)
@@ -99,61 +102,6 @@ func SaveFile(c *gin.Context) {
 	e.ResponseSuccess(c, e.SUCCESS)
 }
 
-// TemplateItem 用于获取所有的模板项
-// 参数:
-// - c *gin.Context: Gin框架的上下文对象,用于处理HTTP请求和响应
-// 返回值:
-// - 无
-//
-//	func TemplateItem(c *gin.Context) {
-//		type Types struct {
-//			Type bool `json:"type"`
-//		}
-//		t := &Types{}
-//		c.BindJSON(&t)
-//		var allKeys []string  // 存储所有检索到的模板项的键名
-//		var cursor uint64 = 0 // 用于分页查询的游标
-//		// 循环检索模板项,直到遍历完所有项或出现错误
-//		for {
-//			keys, newCursor, err := global.Rdb.Scan(context.Background(), cursor, "*", 100).Result() // 每次检索最多100个键名
-//			if err != nil {
-//				// 记录日志并返回错误信息
-//				simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取模板失败")
-//				e.ResponseWithMsg(c, e.ERROR, e.ERROR.GetMsg())
-//				return
-//			}
-//			allKeys = append(allKeys, keys...) // 将检索到的键名添加到allKeys列表
-//			cursor = newCursor                 // 更新游标
-//			if cursor == 0 {
-//				break // 如果游标为0,表示已遍历完所有项,退出循环
-//			}
-//		}
-//		m := make(map[string]any) // 创建一个map用于存储模板项的键名和对应的值
-//		// 遍历所有键名,获取其对应的值
-//		for _, key := range allKeys {
-//			result, err := global.Rdb.Get(context.Background(), key).Result()
-//			if err != nil {
-//				// 记录日志并返回错误信息
-//				simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取模板失败")
-//				e.ResponseWithMsg(c, e.ERROR, e.ERROR.GetMsg())
-//				return
-//			}
-//			file := model.Root{}
-//			//marshal, err := sonic.Marshal(result)
-//			err = sonic.Unmarshal([]byte(result), &file)
-//			if err != nil {
-//				// 记录日志并返回错误信息
-//				simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "序列化失败")
-//				e.ResponseWithMsg(c, e.ERROR, e.ERROR.GetMsg())
-//				return
-//			}
-//			if t.Type == file.Type {
-//				m[key] = result // 将键名和对应的值添加到map中
-//			}
-//		}
-//		// 返回所有模板项的键值对
-//		e.ResponseSuccess(c, m)
-//	}
 func TemplateItem(c *gin.Context) {
 	type Types struct {
 		Type bool `json:"type"`
@@ -183,22 +131,6 @@ func TemplateItem(c *gin.Context) {
 	e.ResponseSuccess(c, result)
 }
 
-// GetTemplate 从服务器获取模板
-//func GetTemplate(c *gin.Context) {
-//	name := c.Query("name")
-//	if name == "" {
-//		e.ResponseWithMsg(c, e.ERROR, "参数错误")
-//		return
-//	}
-//	result, err := global.Rdb.Get(context.Background(), name).Result()
-//	if err != nil {
-//		simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取文件失败")
-//		e.ResponseWithMsg(c, e.ERROR, "获取文件失败")
-//		return
-//	}
-//	e.ResponseSuccess(c, result)
-//}
-
 func GetTemplate(c *gin.Context) {
 	name := c.Query("name")
 	if name == "" {
@@ -237,37 +169,6 @@ func DeleteTemplate(c *gin.Context) {
 	e.ResponseWithMsg(c, e.ERROR, "删除文件失败")
 }
 
-//	func SearchTemplate(c *gin.Context) {
-//		query := c.Query("name")
-//		validate := validator.New()
-//		validate.Var("name", "required")
-//		if query == "" {
-//			e.ResponseWithMsg(c, e.ERROR, "参数错误")
-//			return
-//		}
-//		result, err := global.Rdb.Keys(context.Background(), "*"+query+"*").Result()
-//		if err != nil {
-//			simple_zap.Logger.Error("查询失败", zap.Error(err))
-//			e.ResponseWithMsg(c, e.ERROR, "查询失败")
-//			return
-//		}
-//		if len(result) == 0 {
-//			simple_zap.Logger.Info("查询失败")
-//			e.ResponseWithMsg(c, e.ERROR, "未找到文件")
-//			return
-//		}
-//		m := make(map[string]any)
-//		for _, v := range result {
-//			re, err := global.Rdb.Get(context.Background(), v).Result()
-//			if err != nil {
-//				simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取文件失败")
-//				e.ResponseWithMsg(c, e.ERROR, "获取文件失败")
-//				return
-//			}
-//			m[v] = re
-//		}
-//		e.ResponseSuccess(c, m)
-//	}
 func SearchTemplate(c *gin.Context) {
 	query := c.Query("name")
 	validate := validator.New()
@@ -289,15 +190,5 @@ func SearchTemplate(c *gin.Context) {
 	}
 	err = cursor.All(context.Background(), &result)
 
-	//m := make(map[string]any)
-	//for _, v := range result {
-	// re, err := global.Rdb.Get(context.Background(), v).Result()
-	// if err != nil {
-	//    simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取文件失败")
-	//    e.ResponseWithMsg(c, e.ERROR, "获取文件失败")
-	//    return
-	// }
-	// m[v] = re
-	//}
 	e.ResponseSuccess(c, result)
 }

+ 8 - 5
app/model/model.go

@@ -24,13 +24,15 @@ type GridConfig struct {
 
 type Element struct {
 	GroupId string       `json:"groupId"`
+	Height  float64      `json:"height"`
+	Ratio   float64      `json:"ratio"`
+	Rotate  float64      `json:"rotate"`
+	Style   ElementStyle `json:"style"`
 	Type    string       `json:"type"`
+	Url     string       `json:"url"`
 	Width   float64      `json:"width"`
-	Height  float64      `json:"height"`
 	X       float64      `json:"x"`
 	Y       float64      `json:"y"`
-	Rotate  float64      `json:"rotate"`
-	Style   ElementStyle `json:"style"`
 }
 
 type ElementStyle struct {
@@ -47,6 +49,7 @@ type Data struct {
 }
 
 type Root struct {
-	Type bool `json:"type"`
-	Data Data `json:"data"`
+	Name string `json:"name"`
+	Type bool   `json:"type"`
+	Data Data   `json:"data"`
 }

+ 1 - 1
main.go

@@ -14,7 +14,7 @@ func init() {
 		return
 	}
 	global.SetupMongo()
-	global.SetupRedisLink()
+	//global.SetupRedisLink()
 }
 func main() {
 	err := app.InitRouter()

+ 17 - 0
utils/base64image.go

@@ -0,0 +1,17 @@
+package utils
+
+import "strings"
+
+func ParseBase64ImageString(input string) (contentType string, data string) {
+	parts := strings.Split(input, ",")
+	if len(parts) < 2 {
+		panic("Invalid Base64 image string")
+	}
+
+	contentTypePart := strings.TrimSpace(parts[0])
+	contentTypeParts := strings.Split(contentTypePart, ";")
+	contentType = strings.TrimSpace(contentTypeParts[0])
+
+	data = parts[1]
+	return contentType, data
+}