package controller import ( "bytes" "context" e2 "file_upload/backend/app/e" "file_upload/backend/global" "file_upload/backend/simple_zap" "file_upload/backend/utils" "fmt" "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" "go.mongodb.org/mongo-driver/bson" "go.mongodb.org/mongo-driver/bson/primitive" "go.mongodb.org/mongo-driver/mongo/options" "go.uber.org/zap" "io/ioutil" "net/http" "path" "strconv" "time" ) type Template struct { Name string `json:"name" validate:"required"` Data any `json:"data" validate:"required"` Type int `json:"type" validate:"required"` ImageUrl string `json:"imageUrl" validate:"required"` DataUrl string `json:"dataUrl" validate:"required"` } // SaveTemplate 保存文件到MongoDB // 参数: // - c *gin.Context: Gin框架的上下文对象,用于处理HTTP请求和响应 // 无返回值 func SaveTemplate(c *gin.Context) { // 解析请求体中的文件信息 file := Template{} err := c.BindJSON(&file) uuid := c.Query("uuid") if uuid == "undefined" || uuid == "" || uuid == "null" { uuid = "test" } if file.Name == "" { simple_zap.WithCtx(context.Background()).Sugar().Warn("文件名不能为空") e2.ResponseWithMsg(c, e2.ERROR, "文件名不能为空") return } if err != nil { // 日志记录参数解析失败 simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取参数失败") // 返回参数解析失败的响应 e2.ResponseWithMsg(c, e2.JSONParsingFailed, e2.JSONParsingFailed.GetMsg()) return } // 检查文件是否已存在 filter := bson.M{"name": file.Name} count, err := global.MongoCon.CountDocuments(context.TODO(), filter) if err != nil { // 日志记录查询失败 simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "查询文件是否存在失败") // 返回错误响应 e2.ResponseWithMsg(c, e2.ERROR, e2.ERROR.GetMsg()) return } if count > 0 && file.Type == 1 { err = utils.ParseBase64ImageString(file.ImageUrl, file.Name) if err != nil { simple_zap.WithCtx(context.TODO()).Sugar().Warn(err, "base64解码失败") e2.ResponseWithMsg(c, e2.ERROR, "图片转换失败") return } var url = global.DownloadSetting.Imageurl + file.Name + ".png" err := utils.SaveDataToFile(file.Data, file.Name) if err != nil { simple_zap.WithCtx(context.TODO()).Sugar().Warn(err, "写入文件失败") e2.ResponseWithMsg(c, e2.ERROR, "写入文件失败") } var dataurl = global.DownloadSetting.FileUrl + file.Name + ".json" doc := bson.M{ "name": file.Name, "type": file.Type, "data": nil, "uuid": uuid, "url": url, "dataurl": dataurl, } // 当文件名字相同并且文件类型为1是替换文件 _, err = global.MongoCon.ReplaceOne(context.TODO(), filter, doc, options.Replace().SetUpsert(true)) if err != nil { simple_zap.WithCtx(context.TODO()).Sugar().Warn(err, "替换文件失败") e2.ResponseWithMsg(c, e2.ERROR, "替换文件失败") return } e2.ResponseSuccess(c, e2.SUCCESS) return } unix := time.Now().Unix() formatInt := strconv.FormatInt(unix, 10) err = utils.ParseBase64ImageString(file.ImageUrl, file.Name+formatInt) if err != nil { simple_zap.WithCtx(context.TODO()).Sugar().Warn(err, "base64解码失败") e2.ResponseWithMsg(c, e2.ERROR, "图片转换失败") panic(err) return } var url = global.DownloadSetting.Imageurl + file.Name + formatInt + ".png" err = utils.SaveDataToFile(file.Data, file.Name+formatInt) if err != nil { simple_zap.WithCtx(context.TODO()).Sugar().Warn(err, "写入文件失败") e2.ResponseWithMsg(c, e2.ERROR, "写入文件失败") } var dataurl = global.DownloadSetting.FileUrl + file.Name + formatInt + ".json" doc := bson.M{ "name": file.Name, "type": file.Type, "data": nil, "uuid": uuid, "url": url, "dataurl": dataurl, } // 保存文件到MongoDB _, err = global.MongoCon.InsertOne(context.TODO(), doc) if err != nil { // 日志记录保存文件失败 simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "保存文件失败") // 返回保存文件失败的响应 e2.ResponseWithMsg(c, e2.ERROR, e2.ERROR.GetMsg()) return } // 返回文件保存成功的响应 e2.ResponseSuccess(c, e2.SUCCESS) } // TemplateItem 获取所有模板 func TemplateItem(c *gin.Context) { type Types struct { Type int `json:"type"` } uuid := c.Query("uuid") if uuid == "undefined" || uuid == "" || uuid == "null" { uuid = "test" } t := &Types{} c.BindJSON(&t) filter := bson.M{ "type": t.Type, "uuid": uuid, } var result []bson.M opts := options.Find() opts.SetProjection(bson.M{ "data": 0, }) cur, err := global.MongoCon.Find(context.Background(), filter, opts) if err != nil { // 记录日志并返回错误信息 simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取模板失败") e2.ResponseWithMsg(c, e2.ERROR, e2.ERROR.GetMsg()) return } err = cur.All(context.Background(), &result) if err != nil { // 记录日志并返回错误信息 simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取模板失败") e2.ResponseWithMsg(c, e2.ERROR, e2.ERROR.GetMsg()) return } if result == nil { e2.ResponseWithMsg(c, e2.ERROR, "没有数据") return } e2.ResponseSuccess(c, result) } // GetTemplate 获取模板 func GetTemplate(c *gin.Context) { _id := c.Query("name") uuid := c.Query("uuid") if uuid == "undefined" || uuid == "" || uuid == "null" { uuid = "test" } hex, err2 := primitive.ObjectIDFromHex(_id) if err2 != nil { simple_zap.WithCtx(context.Background()).Sugar().Warn(err2, "_id错误") e2.ResponseWithMsg(c, e2.ERROR, "_id错误") return } var result map[string]interface{} err := global.MongoCon.FindOne(context.Background(), bson.M{"_id": hex}).Decode(&result) if err != nil { simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取文件失败") e2.ResponseWithMsg(c, e2.ERROR, "获取文件失败") return } e2.ResponseSuccess(c, result) } func GetTemplates(c *gin.Context) { name := c.Query("name") uuid := c.Query("uuid") if uuid == "undefined" { uuid = "test" } var result map[string]interface{} err := global.MongoCon.FindOne(context.Background(), bson.M{"name": name}).Decode(&result) if err != nil { simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取文件失败") e2.ResponseWithMsg(c, e2.ERROR, "获取文件失败") return } e2.ResponseSuccess(c, result) } // DeleteTemplate 删除模板 func DeleteTemplate(c *gin.Context) { _id := c.Query("name") uuid := c.Query("uuid") if uuid == "undefined" || uuid == "" || uuid == "null" { uuid = "test" } if _id == "" { e2.ResponseWithMsg(c, e2.ERROR, "参数错误") return } hex, err2 := primitive.ObjectIDFromHex(_id) if err2 != nil { simple_zap.WithCtx(context.Background()).Sugar().Warn(err2, "_id错误") e2.ResponseWithMsg(c, e2.ERROR, "_id错误") return } one, err := global.MongoCon.DeleteOne(context.Background(), bson.M{"_id": hex, "uuid": uuid}) if err != nil { simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "删除文件失败") e2.ResponseWithMsg(c, e2.ERROR, "删除文件失败") return } if one.DeletedCount > 0 { e2.ResponseSuccess(c, one) return } e2.ResponseWithMsg(c, e2.ERROR, "删除文件失败") } // SearchTemplate 搜索模板 func SearchTemplate(c *gin.Context) { query := c.Query("name") uuid := c.Query("uuid") if uuid == "undefined" || uuid == "" || uuid == "null" { uuid = "test" } validate := validator.New() validate.Var("name", "required") if query == "" { e2.ResponseWithMsg(c, e2.ERROR, "参数不弄为空") return } //result, err := global.Rdb.Keys(context.Background(), "*"+query+"*").Result() fileter := bson.M{"name": bson.M{"$regex": query}, "uuid": uuid} var result []bson.M find := options.Find() find.SetProjection(bson.M{ "data": 0, }) cursor, err := global.MongoCon.Find(context.Background(), fileter, find) if err != nil { simple_zap.Logger.Error("查询失败", zap.Error(err)) e2.ResponseWithMsg(c, e2.ERROR, "查询失败") return } err = cursor.All(context.Background(), &result) e2.ResponseSuccess(c, result) } // GetImage 获得图片 func GetImage(c *gin.Context) { typs := c.Query("type") name := c.Query("filename") if name == "" || typs != "upload" { e2.ResponseWithMsg(c, e2.ERROR, "参数错误") return } // 指定图片所在目录的路径 imageDirPath := global.DownloadSetting.Path // 构建图片文件的完整路径 imageFilePath := fmt.Sprintf("%s/%s", imageDirPath, name) file, err := ioutil.ReadFile(imageFilePath) if err != nil { simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取图片失败") e2.ResponseWithMsg(c, e2.ERROR, "获取图片失败") return } // 根据文件扩展名确定 Content-Type ext := path.Ext(name) contentType := "" switch ext { case ".jpg", ".jpeg": contentType = "image/jpeg" case ".png": contentType = "image/png" // 添加更多类型... default: c.AbortWithStatus(http.StatusUnsupportedMediaType) return } c.DataFromReader(http.StatusOK, int64(len(file)), contentType, bytes.NewReader(file), nil) }