upbfs.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package http
  2. import (
  3. "io/ioutil"
  4. "net/http"
  5. "time"
  6. "go-common/library/ecode"
  7. "go-common/library/log"
  8. bm "go-common/library/net/http/blademaster"
  9. )
  10. const maxSize = 1024 * 1024 * 20
  11. func upbfs(c *bm.Context) {
  12. var req = c.Request
  13. // read the file
  14. req.ParseMultipartForm(maxSize)
  15. log.Info("Request Info: %v, %v, %v", req.PostForm, req.Form, req.MultipartForm)
  16. file, _, err := req.FormFile("file")
  17. if err != nil {
  18. renderErrMsg(c, ecode.RequestErr.Code(), "文件为空")
  19. return
  20. }
  21. defer file.Close()
  22. content, err := ioutil.ReadAll(file)
  23. if err != nil {
  24. log.Error("resource uploadFile.ReadAll error(%v)", err)
  25. return
  26. }
  27. // parse file, get type, size
  28. ftype := http.DetectContentType(content)
  29. if ftype != "image/jpeg" && ftype != "image/png" && ftype != "image/webp" && ftype != "image/gif" {
  30. log.Error("filetype not allow file type(%s)", ftype)
  31. renderErrMsg(c, ecode.RequestErr.Code(), "检查文件类型,需为图片")
  32. return
  33. }
  34. fsize := len(content)
  35. if fsize > maxSize {
  36. renderErrMsg(c, ecode.RequestErr.Code(), "文件过大,不支持超过20M的文件")
  37. return
  38. }
  39. // upload file to BFS
  40. c.JSON(tvSrv.Upload(c, "", ftype, time.Now().Unix(), content))
  41. }