bfs.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package http
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "path/filepath"
  6. "go-common/app/service/main/account-recovery/model"
  7. "go-common/library/database/bfs"
  8. "go-common/library/ecode"
  9. "go-common/library/log"
  10. bm "go-common/library/net/http/blademaster"
  11. "github.com/google/uuid"
  12. "github.com/pkg/errors"
  13. )
  14. var _allowedExt = map[string]struct{}{
  15. ".zip": {},
  16. ".rar": {},
  17. ".7z": {},
  18. }
  19. func fileUpload(c *bm.Context) {
  20. defer c.Request.Form.Del("file") // 防止日志不出现
  21. c.Request.ParseMultipartForm(32 << 20)
  22. recoveryFile, fileName, err := func() ([]byte, string, error) {
  23. f, fh, err := c.Request.FormFile("file")
  24. if err != nil {
  25. return nil, "", errors.Wrapf(err, "parse file form file: ")
  26. }
  27. defer f.Close()
  28. data, err := ioutil.ReadAll(f)
  29. if err != nil {
  30. return nil, "", errors.Wrapf(err, "read file form file:")
  31. }
  32. if len(data) <= 0 {
  33. return nil, "", errors.Wrapf(err, "form file data: length: %d", len(data))
  34. }
  35. log.Info("Succeeded to parse file from form file: length: %d", len(data))
  36. return data, fh.Filename, nil
  37. }()
  38. if err != nil {
  39. log.Error("Failed to parse file file: %+v", err)
  40. c.JSON(nil, ecode.RequestErr)
  41. return
  42. }
  43. log.Info("Succeeded to parse recoveryFile data: recoveryFile-length: %d", len(recoveryFile))
  44. //限制文件大小
  45. if len(recoveryFile) > 10*1024*1024 {
  46. log.Error("account-recovery: file is to large(%v)", len(recoveryFile))
  47. c.JSON(nil, ecode.FileTooLarge)
  48. return
  49. }
  50. //限制文件类型 *.zip, *.rar, *.7z
  51. ext := filepath.Ext(fileName)
  52. _, allowed := _allowedExt[ext]
  53. if !allowed {
  54. c.JSON(nil, ecode.BfsUploadFileContentTypeIllegal)
  55. return
  56. }
  57. request := &bfs.Request{
  58. Bucket: "account",
  59. Dir: "recovery",
  60. File: recoveryFile,
  61. Filename: fmt.Sprintf("%s%s", uuid4(), ext),
  62. }
  63. bfsClient := bfs.New(nil)
  64. location, err := bfsClient.Upload(c, request)
  65. if err != nil {
  66. log.Error("err(%+v)", err)
  67. c.JSON(nil, err)
  68. return
  69. }
  70. fileURL := model.BuildFileURL(location)
  71. data := map[string]interface{}{
  72. "url": location,
  73. "fileURL": fileURL,
  74. }
  75. c.JSON(data, nil)
  76. }
  77. func uuid4() string {
  78. return uuid.New().String()
  79. }