upload.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package http
  2. import (
  3. "io/ioutil"
  4. "mime/multipart"
  5. "path"
  6. "strings"
  7. "go-common/app/admin/main/up/conf"
  8. "go-common/app/admin/main/up/service"
  9. "go-common/library/ecode"
  10. "go-common/library/log"
  11. "go-common/library/net/http/blademaster"
  12. "regexp"
  13. "time"
  14. )
  15. //由数字、26个英文字母或者下划线组成的字符串
  16. var reg = regexp.MustCompile(`^\w+$`)
  17. // upload
  18. func upload(c *blademaster.Context) {
  19. var (
  20. fileTpye string
  21. file multipart.File
  22. header *multipart.FileHeader
  23. fileName string
  24. body []byte
  25. location string
  26. err error
  27. res interface{}
  28. errMsg string
  29. )
  30. switch {
  31. default:
  32. if file, header, err = c.Request.FormFile("file"); err != nil {
  33. errMsg = err.Error()
  34. err = ecode.RequestErr
  35. log.Error("c.Request().FormFile(\"file\") error(%v)", err)
  36. break
  37. }
  38. defer file.Close()
  39. fileName = header.Filename
  40. fileTpye = strings.TrimPrefix(path.Ext(fileName), ".")
  41. if body, err = ioutil.ReadAll(file); err != nil {
  42. errMsg = err.Error()
  43. err = ecode.RequestErr
  44. log.Error("ioutil.ReadAll(c.Request().Body) error(%v)", err)
  45. break
  46. }
  47. // 如果不符合规则,就不用文件名
  48. if !reg.MatchString(fileName) {
  49. fileName = ""
  50. }
  51. if location, err = Svc.Upload(c, fileName, fileTpye, time.Now(), body, conf.Conf.BfsConf); err != nil {
  52. errMsg = err.Error()
  53. break
  54. }
  55. res = struct {
  56. URL string `json:"url"`
  57. }{
  58. location,
  59. }
  60. }
  61. if err != nil {
  62. service.BmHTTPErrorWithMsg(c, err, errMsg)
  63. } else {
  64. c.JSON(res, err)
  65. }
  66. }