resource_deal_with_controller.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. // @Author gmy 2024/9/24 17:56:00
  2. package controllers
  3. import (
  4. "eta/eta_hub/models"
  5. "eta/eta_hub/services"
  6. "eta/eta_hub/utils"
  7. "os"
  8. "path"
  9. "time"
  10. )
  11. type ResourceDealWithController struct {
  12. BaseAuthController
  13. }
  14. // FileUpload
  15. // @Title 文件上传
  16. // @Description 文件上传接口
  17. // @Param File query file true "文件"
  18. // @Param AiChatTopicId query int true "主题id"
  19. // @Success 200 {object} models.ResourceResp
  20. // @router /file/upload [post]
  21. func (this *ResourceDealWithController) FileUpload() {
  22. br := new(models.BaseResponse).Init()
  23. defer func() {
  24. this.Data["json"] = br
  25. this.ServeJSON()
  26. }()
  27. f, h, err := this.GetFile("file")
  28. if err != nil {
  29. br.Msg = "获取资源信息失败"
  30. br.ErrMsg = "获取资源信息失败,Err:" + err.Error()
  31. return
  32. }
  33. /*fileData, e := ioutil.ReadAll(f)
  34. if e != nil {
  35. br.Msg = "上传失败"
  36. br.ErrMsg = "读取文件失败, Err: " + e.Error()
  37. return
  38. }
  39. pass := filetype.IsImage(fileData)
  40. if !pass {
  41. br.Msg = "文件格式有误"
  42. br.ErrMsg = "文件格式有误"
  43. return
  44. }*/
  45. uploadFileName := h.Filename //上传的文件名
  46. ext := path.Ext(h.Filename)
  47. dateDir := time.Now().Format("20060102")
  48. uploadDir := utils.STATIC_DIR + "hongze/" + dateDir
  49. err = os.MkdirAll(uploadDir, utils.DIR_MOD)
  50. if err != nil {
  51. br.Msg = "存储目录创建失败"
  52. br.ErrMsg = "存储目录创建失败,Err:" + err.Error()
  53. return
  54. }
  55. randStr := utils.GetRandStringNoSpecialChar(28)
  56. fileName := randStr + ext
  57. fpath := uploadDir + "/" + fileName
  58. defer f.Close() //关闭上传文件
  59. err = this.SaveToFile("file", fpath)
  60. if err != nil {
  61. br.Msg = "文件上传失败"
  62. br.ErrMsg = "文件上传失败,Err:" + err.Error()
  63. return
  64. }
  65. resourceUrl := ``
  66. ossClient := services.NewOssClient()
  67. if ossClient == nil {
  68. br.Msg = "上传失败"
  69. br.ErrMsg = "初始化OSS服务失败"
  70. return
  71. }
  72. resourceUrl, err = ossClient.UploadFile(fileName, fpath, "")
  73. if err != nil {
  74. br.Msg = "文件上传失败"
  75. br.ErrMsg = "文件上传失败,Err:" + err.Error()
  76. return
  77. }
  78. defer func() {
  79. os.Remove(fpath)
  80. }()
  81. item := new(models.Resource)
  82. item.ResourceUrl = resourceUrl
  83. item.ResourceType = 1
  84. item.CreateTime = time.Now()
  85. newId, err := models.AddResource(item)
  86. if err != nil {
  87. br.Msg = "资源上传失败"
  88. br.ErrMsg = "资源上传失败,Err:" + err.Error()
  89. return
  90. }
  91. resp := models.ResourceResp{
  92. Id: newId,
  93. ResourceUrl: resourceUrl,
  94. ResourceName: uploadFileName,
  95. }
  96. br.Msg = "上传成功"
  97. br.Ret = 200
  98. br.Data = resp
  99. return
  100. }