resource.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package controllers
  2. import (
  3. "hongze/hongze_cygx/models"
  4. "hongze/hongze_cygx/services"
  5. "hongze/hongze_cygx/utils"
  6. "os"
  7. "path"
  8. "time"
  9. )
  10. //资源管理-图片上传,合同上传等
  11. type ResourceController struct {
  12. BaseAuthController
  13. }
  14. // @Title 图片上传
  15. // @Description 图片上传接口
  16. // @Param file query file true "文件"
  17. // @Success 200 新增成功
  18. // @router /image/upload [post]
  19. func (this *ResourceController) 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 := "static/temp/" + dateDir
  34. err = os.MkdirAll(uploadDir, 777)
  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. //
  51. ////上传到阿里云
  52. //resourceUrl, err := services.UploadAliyun(fileName, fpath)
  53. //if err != nil {
  54. // br.Msg = "文件上传失败"
  55. // br.ErrMsg = "文件上传失败,Err:" + err.Error()
  56. // return
  57. //}
  58. savePath := uploadDir + time.Now().Format("200601/20060102/")
  59. savePath += fileName
  60. //上传到阿里云
  61. err = services.UploadFileToAliyun("", fpath, savePath)
  62. if err != nil {
  63. br.Msg = "文件上传失败"
  64. br.ErrMsg = "文件上传失败,Err:" + err.Error()
  65. return
  66. }
  67. fileHost := "https://hzstatic.hzinsights.com/"
  68. resourceUrl := fileHost + savePath
  69. defer func() {
  70. os.Remove(fpath)
  71. }()
  72. item := new(models.Resource)
  73. item.ResourceUrl = resourceUrl
  74. item.ResourceType = 1
  75. item.CreateTime = time.Now()
  76. newId, err := models.AddResource(item)
  77. if err != nil {
  78. br.Msg = "资源上传失败"
  79. br.ErrMsg = "资源上传失败,Err:" + err.Error()
  80. return
  81. }
  82. resp := new(models.ResourceResp)
  83. resp.Id = newId
  84. resp.ResourceUrl = resourceUrl
  85. br.Msg = "上传成功"
  86. br.Ret = 200
  87. br.Success = true
  88. br.Data = resp
  89. return
  90. }