file.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package handlers
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. "github.com/spf13/viper"
  6. "go.uber.org/zap"
  7. "passport/app/models"
  8. "passport/logger"
  9. "passport/pkg/ierr"
  10. "passport/pkg/util"
  11. "path/filepath"
  12. )
  13. /**
  14. * showdoc
  15. * @catalog 文件上传
  16. * @title 文件上传通用接口
  17. * @description 文件上传通用接口
  18. * @method POST
  19. * @url ~/v1/file/upload
  20. * @return {"code":0,"data":{"url":"/xRTZHWUsaD6H_715747502.mp4","name":"认真且怂.mp4","size":3409702,"ext":".mp4","user_id":"26640398931722340"}}
  21. * @return_param url string url地址
  22. * @return_param name string 文件名
  23. * @return_param size int 文件大小
  24. * @return_param ext string 文件扩展名
  25. * @return_param user_id string 用户id
  26. * @remark 无
  27. * @number 1
  28. */
  29. func UploadFile(c *gin.Context) {
  30. var userId = c.GetString("uid")
  31. var f, err = c.FormFile("file")
  32. if err != nil {
  33. ResponseErr(c, ierr.NewIError(ierr.ReceiveRequestFileFail, err.Error()))
  34. return
  35. }
  36. var saveDir = viper.GetString("file.path")
  37. var host = viper.GetString("file.host")
  38. var name = fmt.Sprintf("%s_%d", util.RandomString(12), util.Now13()%1e9) + filepath.Ext(f.Filename)
  39. var path = filepath.Join(saveDir, name)
  40. var fileModel = &models.File{
  41. Url: host + name,
  42. Name: f.Filename,
  43. Path: path,
  44. Size: f.Size,
  45. Ext: filepath.Ext(f.Filename),
  46. UserId: "mock_user_id",
  47. }
  48. err = c.SaveUploadedFile(f, path)
  49. if err != nil {
  50. logger.Error("[UploadFile] save file to disk error",
  51. zap.Any("file", fileModel),
  52. zap.Error(err))
  53. ResponseErr(c, err)
  54. return
  55. }
  56. err = fileModel.Save()
  57. if err != nil {
  58. logger.Error("[UploadFile] save file info to db error",
  59. zap.Any("file", fileModel),
  60. zap.Error(err))
  61. ResponseErr(c, err)
  62. return
  63. }
  64. var resp = models.FileResponse{
  65. Url: fileModel.Url,
  66. Name: fileModel.Name,
  67. Size: fileModel.Size,
  68. Ext: fileModel.Ext,
  69. UserId: userId,
  70. }
  71. ResponseSuccess(c, resp)
  72. }