banner.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package controllers
  2. import (
  3. "eta/eta_api/models"
  4. "eta/eta_api/services"
  5. "eta/eta_api/utils"
  6. "os"
  7. "path"
  8. "time"
  9. )
  10. // banner
  11. type BannerController struct {
  12. BaseAuthController
  13. }
  14. // @Title 图片上传
  15. // @Description 图片上传接口
  16. // @Param File query file true "文件"
  17. // @Success 200 新增成功
  18. // @router /upload [post]
  19. func (this *BannerController) Upload() {
  20. br := new(models.BaseResponse).Init()
  21. defer func() {
  22. this.Data["json"] = br
  23. this.ServeJSON()
  24. }()
  25. f, h, err := this.GetFile("file")
  26. if err != nil {
  27. br.Msg = "获取资源信息失败"
  28. br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
  29. return
  30. }
  31. ext := path.Ext(h.Filename)
  32. dateDir := time.Now().Format("20060102")
  33. uploadDir := utils.STATIC_DIR + "hongze/" + dateDir
  34. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  35. if err != nil {
  36. br.Msg = "存储目录创建失败"
  37. br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
  38. return
  39. }
  40. randStr := utils.GetRandStringNoSpecialChar(28)
  41. fileName := randStr + ext
  42. fpath := uploadDir + "/" + fileName
  43. defer f.Close() //关闭上传文件
  44. err = this.SaveToFile("file", fpath)
  45. if err != nil {
  46. br.Msg = "文件上传失败"
  47. br.ErrMsg = "文件上传失败,Err:" + err.Error()
  48. return
  49. }
  50. resourceUrl := ``
  51. //上传到阿里云 和 minio
  52. if utils.ObjectStorageClient == "minio" {
  53. resourceUrl, err = services.UploadImgToMinIo(fileName, fpath)
  54. if err != nil {
  55. br.Msg = "文件上传失败"
  56. br.ErrMsg = "文件上传失败,Err:" + err.Error()
  57. return
  58. }
  59. } else {
  60. resourceUrl, err = services.UploadAliyunV2(fileName, fpath)
  61. if err != nil {
  62. br.Msg = "文件上传失败"
  63. br.ErrMsg = "文件上传失败,Err:" + err.Error()
  64. return
  65. }
  66. }
  67. defer func() {
  68. os.Remove(fpath)
  69. }()
  70. item := new(models.Resource)
  71. item.ResourceUrl = resourceUrl
  72. item.ResourceType = 1
  73. item.CreateTime = time.Now()
  74. newId, err := models.AddResource(item)
  75. if err != nil {
  76. br.Msg = "资源上传失败"
  77. br.ErrMsg = "资源上传失败,Err:" + err.Error()
  78. return
  79. }
  80. resp := new(models.ResourceResp)
  81. resp.Id = newId
  82. resp.ResourceUrl = resourceUrl
  83. br.Msg = "上传成功"
  84. br.Ret = 200
  85. br.Success = true
  86. br.Data = resp
  87. return
  88. }