file.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. package controller
  2. import (
  3. "bytes"
  4. "context"
  5. "file_upload/app/e"
  6. "file_upload/global"
  7. "file_upload/simple_zap"
  8. "file_upload/utils"
  9. "fmt"
  10. "github.com/gin-gonic/gin"
  11. "github.com/go-playground/validator/v10"
  12. "go.mongodb.org/mongo-driver/bson"
  13. "go.mongodb.org/mongo-driver/mongo/options"
  14. "go.uber.org/zap"
  15. "io/ioutil"
  16. "net/http"
  17. "path"
  18. )
  19. type Template struct {
  20. Name string `json:"name" validate:"required"`
  21. Data any `json:"data" validate:"required"`
  22. Type int `json:"type" validate:"required"`
  23. ImageUrl string `json:"imageUrl" validate:"required"`
  24. }
  25. // SaveTemplate 保存文件到MongoDB
  26. // 参数:
  27. // - c *gin.Context: Gin框架的上下文对象,用于处理HTTP请求和响应
  28. // 无返回值
  29. func SaveTemplate(c *gin.Context) {
  30. // 解析请求体中的文件信息
  31. file := Template{}
  32. err := c.BindJSON(&file)
  33. if err != nil {
  34. // 日志记录参数解析失败
  35. simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取参数失败")
  36. // 返回参数解析失败的响应
  37. e.ResponseWithMsg(c, e.JSONParsingFailed, e.JSONParsingFailed.GetMsg())
  38. return
  39. }
  40. // 检查文件是否已存在
  41. filter := bson.M{"name": file.Name}
  42. count, err := global.MongoCon.CountDocuments(context.TODO(), filter)
  43. if err != nil {
  44. // 日志记录查询失败
  45. simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "查询文件是否存在失败")
  46. // 返回错误响应
  47. e.ResponseWithMsg(c, e.ERROR, e.ERROR.GetMsg())
  48. return
  49. }
  50. if count > 0 {
  51. // 返回文件已存在的响应
  52. e.ResponseWithMsg(c, e.AlreadyExists, e.AlreadyExists.GetMsg())
  53. return
  54. }
  55. err = utils.ParseBase64ImageString(file.ImageUrl, file.Name)
  56. if err != nil {
  57. simple_zap.WithCtx(context.TODO()).Sugar().Warn(err, "base64解码失败")
  58. e.ResponseWithMsg(c, e.ERROR, "图片转换失败")
  59. return
  60. }
  61. var url = global.DownloadSetting.Path + file.Name + ".png"
  62. doc := bson.M{
  63. "name": file.Name,
  64. "type": file.Type,
  65. "data": file.Data,
  66. "url": url,
  67. }
  68. // 保存文件到MongoDB
  69. _, err = global.MongoCon.InsertOne(context.TODO(), doc)
  70. if err != nil {
  71. // 日志记录保存文件失败
  72. simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "保存文件失败")
  73. // 返回保存文件失败的响应
  74. e.ResponseWithMsg(c, e.ERROR, e.ERROR.GetMsg())
  75. return
  76. }
  77. // 返回文件保存成功的响应
  78. e.ResponseSuccess(c, e.SUCCESS)
  79. }
  80. // TemplateItem 获取所有模板
  81. func TemplateItem(c *gin.Context) {
  82. type Types struct {
  83. Type int `json:"type"`
  84. }
  85. t := &Types{}
  86. c.BindJSON(&t)
  87. filter := bson.M{
  88. "type": t.Type,
  89. }
  90. var result []bson.M
  91. opts := options.Find()
  92. opts.SetProjection(bson.M{
  93. "_id": 0,
  94. "data": 0,
  95. })
  96. cur, err := global.MongoCon.Find(context.Background(), filter, opts)
  97. if err != nil {
  98. // 记录日志并返回错误信息
  99. simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取模板失败")
  100. e.ResponseWithMsg(c, e.ERROR, e.ERROR.GetMsg())
  101. return
  102. }
  103. err = cur.All(context.Background(), &result)
  104. if err != nil {
  105. // 记录日志并返回错误信息
  106. simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取模板失败")
  107. e.ResponseWithMsg(c, e.ERROR, e.ERROR.GetMsg())
  108. return
  109. }
  110. e.ResponseSuccess(c, result)
  111. }
  112. // GetTemplate 获取模板
  113. func GetTemplate(c *gin.Context) {
  114. name := c.Query("name")
  115. if name == "" {
  116. e.ResponseWithMsg(c, e.ERROR, "参数错误")
  117. return
  118. }
  119. var result map[string]interface{}
  120. err := global.MongoCon.FindOne(context.Background(), bson.M{"name": name}).Decode(&result)
  121. if err != nil {
  122. simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取文件失败")
  123. e.ResponseWithMsg(c, e.ERROR, "获取文件失败")
  124. return
  125. }
  126. e.ResponseSuccess(c, result)
  127. }
  128. // DeleteTemplate 删除模板
  129. func DeleteTemplate(c *gin.Context) {
  130. name := c.Query("name")
  131. if name == "" {
  132. e.ResponseWithMsg(c, e.ERROR, "参数错误")
  133. return
  134. }
  135. one, err := global.MongoCon.DeleteOne(context.Background(), bson.M{"name": name})
  136. //err := global.Rdb.Del(context.Background(), name).Err()
  137. if err != nil {
  138. simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "删除文件失败")
  139. e.ResponseWithMsg(c, e.ERROR, "删除文件失败")
  140. return
  141. }
  142. if one.DeletedCount > 0 {
  143. e.ResponseSuccess(c, one)
  144. return
  145. }
  146. e.ResponseWithMsg(c, e.ERROR, "删除文件失败")
  147. }
  148. // SearchTemplate 搜索模板
  149. func SearchTemplate(c *gin.Context) {
  150. query := c.Query("name")
  151. validate := validator.New()
  152. validate.Var("name", "required")
  153. if query == "" {
  154. e.ResponseWithMsg(c, e.ERROR, "参数不弄为空")
  155. return
  156. }
  157. //result, err := global.Rdb.Keys(context.Background(), "*"+query+"*").Result()
  158. fileter := bson.M{"name": bson.M{"$regex": query}}
  159. var result []bson.M
  160. find := options.Find()
  161. find.SetProjection(bson.M{
  162. "_id": 0,
  163. "data": 0,
  164. })
  165. cursor, err := global.MongoCon.Find(context.Background(), fileter, find)
  166. if err != nil {
  167. simple_zap.Logger.Error("查询失败", zap.Error(err))
  168. e.ResponseWithMsg(c, e.ERROR, "查询失败")
  169. return
  170. }
  171. err = cursor.All(context.Background(), &result)
  172. e.ResponseSuccess(c, result)
  173. }
  174. // GetImage 获得图片
  175. func GetImage(c *gin.Context) {
  176. typs := c.Query("type")
  177. name := c.Query("filename")
  178. if name == "" || typs != "upload" {
  179. e.ResponseWithMsg(c, e.ERROR, "参数错误")
  180. return
  181. }
  182. // 指定图片所在目录的路径
  183. imageDirPath := "./upload"
  184. // 构建图片文件的完整路径
  185. imageFilePath := fmt.Sprintf("%s/%s", imageDirPath, name)
  186. file, err := ioutil.ReadFile(imageFilePath)
  187. if err != nil {
  188. simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取图片失败")
  189. e.ResponseWithMsg(c, e.ERROR, "获取图片失败")
  190. return
  191. }
  192. // 根据文件扩展名确定 Content-Type
  193. ext := path.Ext(name)
  194. contentType := ""
  195. switch ext {
  196. case ".jpg", ".jpeg":
  197. contentType = "image/jpeg"
  198. case ".png":
  199. contentType = "image/png"
  200. // 添加更多类型...
  201. default:
  202. c.AbortWithStatus(http.StatusUnsupportedMediaType)
  203. return
  204. }
  205. c.DataFromReader(http.StatusOK, int64(len(file)), contentType, bytes.NewReader(file), nil)
  206. }