upload.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package http
  2. import (
  3. "crypto/md5"
  4. "fmt"
  5. "io/ioutil"
  6. "strconv"
  7. "strings"
  8. "time"
  9. "go-common/app/admin/main/push/conf"
  10. "go-common/app/admin/main/push/model"
  11. "go-common/library/ecode"
  12. "go-common/library/log"
  13. bm "go-common/library/net/http/blademaster"
  14. )
  15. func upload(c *bm.Context) {
  16. var (
  17. err error
  18. req = c.Request
  19. )
  20. req.ParseMultipartForm(1024 * 1024 * 1024) // 1G
  21. fileName := req.FormValue("filename")
  22. if fileName == "" {
  23. log.Error("filename is empty")
  24. c.JSON(nil, ecode.RequestErr)
  25. return
  26. }
  27. file, header, err := req.FormFile("file")
  28. if err != nil {
  29. log.Error("req.FormFile() error(%v)", err)
  30. c.JSON(nil, err)
  31. return
  32. }
  33. defer file.Close()
  34. bs, err := ioutil.ReadAll(file)
  35. if err != nil {
  36. log.Error("ioutil.ReadAll() error(%v)", err)
  37. c.JSON(nil, err)
  38. return
  39. }
  40. typ, _ := strconv.Atoi(req.FormValue("type"))
  41. if typ == model.UploadTypeMid {
  42. if err = pushSrv.CheckUploadMid(c, bs); err != nil {
  43. c.JSON(nil, err)
  44. return
  45. }
  46. } else if typ == model.UploadTypeToken {
  47. if err = pushSrv.CheckUploadToken(c, bs); err != nil {
  48. c.JSON(nil, err)
  49. return
  50. }
  51. } else {
  52. log.Error("type(%d) invalid", typ)
  53. c.JSON(nil, ecode.RequestErr)
  54. return
  55. }
  56. dir := fmt.Sprintf("%s/%s", strings.TrimSuffix(conf.Conf.Cfg.MountDir, "/"), time.Now().Format("20060102"))
  57. path := fmt.Sprintf("%s/%x", dir, md5.Sum([]byte(fileName)))
  58. if err = pushSrv.Upload(c, dir, path, bs); err != nil {
  59. log.Error("upload file file(%s) error(%v)", path, err)
  60. c.JSON(nil, err)
  61. return
  62. }
  63. c.JSON(struct {
  64. Name string `json:"name"`
  65. Path string `json:"path"`
  66. }{
  67. Name: header.Filename,
  68. Path: path,
  69. }, nil)
  70. }
  71. func upimg(ctx *bm.Context) {
  72. f, h, err := ctx.Request.FormFile("file")
  73. if err != nil {
  74. log.Error("upimg error(%v)", err)
  75. ctx.JSON(nil, err)
  76. return
  77. }
  78. defer f.Close()
  79. url, err := pushSrv.Upimg(ctx, f, h)
  80. if err != nil {
  81. ctx.JSON(nil, err)
  82. return
  83. }
  84. ctx.JSON(map[string]string{"url": url}, nil)
  85. }