file.go 9.0 KB

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