file.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. package controller
  2. import (
  3. "bytes"
  4. "context"
  5. e2 "file_upload/backend/app/e"
  6. "file_upload/backend/global"
  7. "file_upload/backend/simple_zap"
  8. "file_upload/backend/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/bson/primitive"
  14. "go.mongodb.org/mongo-driver/mongo/options"
  15. "go.uber.org/zap"
  16. "io/ioutil"
  17. "net/http"
  18. "path"
  19. "strconv"
  20. "time"
  21. )
  22. type Template struct {
  23. Name string `json:"name" validate:"required"`
  24. Data any `json:"data" validate:"required"`
  25. Type int `json:"type" validate:"required"`
  26. ImageUrl string `json:"imageUrl" validate:"required"`
  27. }
  28. // SaveTemplate 保存文件到MongoDB
  29. // 参数:
  30. // - c *gin.Context: Gin框架的上下文对象,用于处理HTTP请求和响应
  31. // 无返回值
  32. func SaveTemplate(c *gin.Context) {
  33. // 解析请求体中的文件信息
  34. file := Template{}
  35. err := c.BindJSON(&file)
  36. uuid := c.Query("uuid")
  37. if uuid == "undefined" || uuid == "" || uuid == "null" {
  38. uuid = "test"
  39. }
  40. if file.Name == "" {
  41. simple_zap.WithCtx(context.Background()).Sugar().Warn("文件名不能为空")
  42. e2.ResponseWithMsg(c, e2.ERROR, "文件名不能为空")
  43. return
  44. }
  45. if err != nil {
  46. // 日志记录参数解析失败
  47. simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取参数失败")
  48. // 返回参数解析失败的响应
  49. e2.ResponseWithMsg(c, e2.JSONParsingFailed, e2.JSONParsingFailed.GetMsg())
  50. return
  51. }
  52. // 检查文件是否已存在
  53. filter := bson.M{"name": file.Name}
  54. count, err := global.MongoCon.CountDocuments(context.TODO(), filter)
  55. if err != nil {
  56. // 日志记录查询失败
  57. simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "查询文件是否存在失败")
  58. // 返回错误响应
  59. e2.ResponseWithMsg(c, e2.ERROR, e2.ERROR.GetMsg())
  60. return
  61. }
  62. if count > 0 && file.Type == 1 {
  63. err = utils.ParseBase64ImageString(file.ImageUrl, file.Name)
  64. if err != nil {
  65. simple_zap.WithCtx(context.TODO()).Sugar().Warn(err, "base64解码失败")
  66. e2.ResponseWithMsg(c, e2.ERROR, "图片转换失败")
  67. panic(err)
  68. return
  69. }
  70. var url = global.DownloadSetting.Imageurl + file.Name + ".png"
  71. doc := bson.M{
  72. "name": file.Name,
  73. "type": file.Type,
  74. "data": file.Data,
  75. "uuid": uuid,
  76. "url": url,
  77. }
  78. // 当文件名字相同并且文件类型为1是替换文件
  79. _, err := global.MongoCon.ReplaceOne(context.TODO(), filter, doc, options.Replace().SetUpsert(true))
  80. if err != nil {
  81. simple_zap.WithCtx(context.TODO()).Sugar().Warn(err, "替换文件失败")
  82. e2.ResponseWithMsg(c, e2.ERROR, "替换文件失败")
  83. return
  84. }
  85. e2.ResponseSuccess(c, e2.SUCCESS)
  86. return
  87. }
  88. unix := time.Now().Unix()
  89. formatInt := strconv.FormatInt(unix, 10)
  90. err = utils.ParseBase64ImageString(file.ImageUrl, file.Name+formatInt)
  91. if err != nil {
  92. simple_zap.WithCtx(context.TODO()).Sugar().Warn(err, "base64解码失败")
  93. e2.ResponseWithMsg(c, e2.ERROR, "图片转换失败")
  94. panic(err)
  95. return
  96. }
  97. var url = global.DownloadSetting.Imageurl + file.Name + formatInt + ".png"
  98. doc := bson.M{
  99. "name": file.Name,
  100. "type": file.Type,
  101. "data": file.Data,
  102. "uuid": uuid,
  103. "url": url,
  104. }
  105. // 保存文件到MongoDB
  106. _, err = global.MongoCon.InsertOne(context.TODO(), doc)
  107. if err != nil {
  108. // 日志记录保存文件失败
  109. simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "保存文件失败")
  110. // 返回保存文件失败的响应
  111. e2.ResponseWithMsg(c, e2.ERROR, e2.ERROR.GetMsg())
  112. return
  113. }
  114. // 返回文件保存成功的响应
  115. e2.ResponseSuccess(c, e2.SUCCESS)
  116. }
  117. // TemplateItem 获取所有模板
  118. func TemplateItem(c *gin.Context) {
  119. type Types struct {
  120. Type int `json:"type"`
  121. }
  122. uuid := c.Query("uuid")
  123. if uuid == "undefined" || uuid == "" || uuid == "null" {
  124. uuid = "test"
  125. }
  126. t := &Types{}
  127. c.BindJSON(&t)
  128. filter := bson.M{
  129. "type": t.Type,
  130. "uuid": uuid,
  131. }
  132. var result []bson.M
  133. opts := options.Find()
  134. opts.SetProjection(bson.M{
  135. "data": 0,
  136. })
  137. cur, err := global.MongoCon.Find(context.Background(), filter, opts)
  138. if err != nil {
  139. // 记录日志并返回错误信息
  140. simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取模板失败")
  141. e2.ResponseWithMsg(c, e2.ERROR, e2.ERROR.GetMsg())
  142. return
  143. }
  144. err = cur.All(context.Background(), &result)
  145. if err != nil {
  146. // 记录日志并返回错误信息
  147. simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取模板失败")
  148. e2.ResponseWithMsg(c, e2.ERROR, e2.ERROR.GetMsg())
  149. return
  150. }
  151. if result == nil {
  152. e2.ResponseWithMsg(c, e2.ERROR, "没有数据")
  153. return
  154. }
  155. e2.ResponseSuccess(c, result)
  156. }
  157. // GetTemplate 获取模板
  158. func GetTemplate(c *gin.Context) {
  159. _id := c.Query("name")
  160. uuid := c.Query("uuid")
  161. if uuid == "undefined" || uuid == "" || uuid == "null" {
  162. uuid = "test"
  163. }
  164. hex, err2 := primitive.ObjectIDFromHex(_id)
  165. if err2 != nil {
  166. simple_zap.WithCtx(context.Background()).Sugar().Warn(err2, "_id错误")
  167. e2.ResponseWithMsg(c, e2.ERROR, "_id错误")
  168. return
  169. }
  170. var result map[string]interface{}
  171. err := global.MongoCon.FindOne(context.Background(), bson.M{"_id": hex}).Decode(&result)
  172. if err != nil {
  173. simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取文件失败")
  174. e2.ResponseWithMsg(c, e2.ERROR, "获取文件失败")
  175. return
  176. }
  177. e2.ResponseSuccess(c, result)
  178. }
  179. func GetTemplates(c *gin.Context) {
  180. name := c.Query("name")
  181. uuid := c.Query("uuid")
  182. if uuid == "undefined" {
  183. uuid = "test"
  184. }
  185. //hex, err2 := primitive.ObjectIDFromHex(_id)
  186. //if err2 != nil {
  187. // simple_zap.WithCtx(context.Background()).Sugar().Warn(err2, "_id错误")
  188. // e2.ResponseWithMsg(c, e2.ERROR, "_id错误")
  189. // return
  190. //}
  191. var result map[string]interface{}
  192. err := global.MongoCon.FindOne(context.Background(), bson.M{"name": name}).Decode(&result)
  193. if err != nil {
  194. simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取文件失败")
  195. e2.ResponseWithMsg(c, e2.ERROR, "获取文件失败")
  196. return
  197. }
  198. e2.ResponseSuccess(c, result)
  199. }
  200. // DeleteTemplate 删除模板
  201. func DeleteTemplate(c *gin.Context) {
  202. _id := c.Query("name")
  203. uuid := c.Query("uuid")
  204. if uuid == "undefined" || uuid == "" || uuid == "null" {
  205. uuid = "test"
  206. }
  207. if _id == "" {
  208. e2.ResponseWithMsg(c, e2.ERROR, "参数错误")
  209. return
  210. }
  211. hex, err2 := primitive.ObjectIDFromHex(_id)
  212. if err2 != nil {
  213. simple_zap.WithCtx(context.Background()).Sugar().Warn(err2, "_id错误")
  214. e2.ResponseWithMsg(c, e2.ERROR, "_id错误")
  215. return
  216. }
  217. one, err := global.MongoCon.DeleteOne(context.Background(), bson.M{"_id": hex, "uuid": uuid})
  218. if err != nil {
  219. simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "删除文件失败")
  220. e2.ResponseWithMsg(c, e2.ERROR, "删除文件失败")
  221. return
  222. }
  223. if one.DeletedCount > 0 {
  224. e2.ResponseSuccess(c, one)
  225. return
  226. }
  227. e2.ResponseWithMsg(c, e2.ERROR, "删除文件失败")
  228. }
  229. // SearchTemplate 搜索模板
  230. func SearchTemplate(c *gin.Context) {
  231. query := c.Query("name")
  232. uuid := c.Query("uuid")
  233. if uuid == "undefined" || uuid == "" || uuid == "null" {
  234. uuid = "test"
  235. }
  236. validate := validator.New()
  237. validate.Var("name", "required")
  238. if query == "" {
  239. e2.ResponseWithMsg(c, e2.ERROR, "参数不弄为空")
  240. return
  241. }
  242. //result, err := global.Rdb.Keys(context.Background(), "*"+query+"*").Result()
  243. fileter := bson.M{"name": bson.M{"$regex": query}, "uuid": uuid}
  244. var result []bson.M
  245. find := options.Find()
  246. find.SetProjection(bson.M{
  247. "data": 0,
  248. })
  249. cursor, err := global.MongoCon.Find(context.Background(), fileter, find)
  250. if err != nil {
  251. simple_zap.Logger.Error("查询失败", zap.Error(err))
  252. e2.ResponseWithMsg(c, e2.ERROR, "查询失败")
  253. return
  254. }
  255. err = cursor.All(context.Background(), &result)
  256. e2.ResponseSuccess(c, result)
  257. }
  258. // GetImage 获得图片
  259. func GetImage(c *gin.Context) {
  260. typs := c.Query("type")
  261. name := c.Query("filename")
  262. if name == "" || typs != "upload" {
  263. e2.ResponseWithMsg(c, e2.ERROR, "参数错误")
  264. return
  265. }
  266. // 指定图片所在目录的路径
  267. imageDirPath := global.DownloadSetting.Path
  268. // 构建图片文件的完整路径
  269. imageFilePath := fmt.Sprintf("%s/%s", imageDirPath, name)
  270. file, err := ioutil.ReadFile(imageFilePath)
  271. if err != nil {
  272. simple_zap.WithCtx(context.Background()).Sugar().Warn(err, "获取图片失败")
  273. e2.ResponseWithMsg(c, e2.ERROR, "获取图片失败")
  274. return
  275. }
  276. // 根据文件扩展名确定 Content-Type
  277. ext := path.Ext(name)
  278. contentType := ""
  279. switch ext {
  280. case ".jpg", ".jpeg":
  281. contentType = "image/jpeg"
  282. case ".png":
  283. contentType = "image/png"
  284. // 添加更多类型...
  285. default:
  286. c.AbortWithStatus(http.StatusUnsupportedMediaType)
  287. return
  288. }
  289. c.DataFromReader(http.StatusOK, int64(len(file)), contentType, bytes.NewReader(file), nil)
  290. }