file.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package admin
  2. import (
  3. "Gwen/global"
  4. "Gwen/http/response"
  5. "Gwen/lib/upload"
  6. "fmt"
  7. "github.com/gin-gonic/gin"
  8. "os"
  9. "time"
  10. )
  11. type File struct {
  12. }
  13. // OssToken 文件
  14. // @Tags 文件
  15. // @Summary 获取ossToken
  16. // @Description 获取ossToken
  17. // @Accept json
  18. // @Produce json
  19. // @Success 200 {object} response.Response
  20. // @Failure 500 {object} response.Response
  21. // @Router /admin/file/oss_token [get]
  22. // @Security token
  23. func (f *File) OssToken(c *gin.Context) {
  24. token := global.Oss.GetPolicyToken("")
  25. response.Success(c, token)
  26. }
  27. type FileBack struct {
  28. upload.CallbackBaseForm
  29. Url string `json:"url"`
  30. }
  31. // Notify 上传成功后回调
  32. func (f *File) Notify(c *gin.Context) {
  33. res := global.Oss.Verify(c.Request)
  34. if !res {
  35. response.Fail(c, 101, "权限错误")
  36. return
  37. }
  38. fm := &FileBack{}
  39. if err := c.ShouldBind(fm); err != nil {
  40. fmt.Println(err)
  41. }
  42. fm.Url = global.Config.Oss.Host + "/" + fm.Filename
  43. response.Success(c, fm)
  44. }
  45. // Upload 上传文件到本地
  46. // @Tags 文件
  47. // @Summary 上传文件到本地
  48. // @Description 上传文件到本地
  49. // @Accept multipart/form-data
  50. // @Produce json
  51. // @Param file formData file true "上传文件示例"
  52. // @Success 200 {object} response.Response
  53. // @Failure 500 {object} response.Response
  54. // @Router /admin/file/upload [post]
  55. // @Security token
  56. func (f *File) Upload(c *gin.Context) {
  57. file, _ := c.FormFile("file")
  58. timePath := time.Now().Format("20060102") + "/"
  59. webPath := "/upload/" + timePath
  60. path := global.Config.Gin.ResourcesPath + webPath
  61. dst := path + file.Filename
  62. err := os.MkdirAll(path, os.ModePerm)
  63. if err != nil {
  64. return
  65. }
  66. // 上传文件至指定目录
  67. err = c.SaveUploadedFile(file, dst)
  68. if err != nil {
  69. return
  70. }
  71. // 返回文件web地址
  72. response.Success(c, gin.H{
  73. "url": webPath + file.Filename,
  74. })
  75. }