upload.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package http
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "net/http"
  6. "path"
  7. "time"
  8. "go-common/library/ecode"
  9. "go-common/library/log"
  10. bm "go-common/library/net/http/blademaster"
  11. )
  12. const (
  13. maxFileSize = 20 << 20
  14. )
  15. func upload(c *bm.Context) {
  16. c.Request.ParseMultipartForm(maxFileSize)
  17. imageFile, header, err := c.Request.FormFile("file")
  18. if err != nil {
  19. log.Error("upload fail, no field file")
  20. c.JSON(nil, err)
  21. return
  22. }
  23. if header.Size > maxFileSize {
  24. c.JSON(nil, ecode.MCNContractFileSize)
  25. return
  26. }
  27. fileExt := path.Ext(header.Filename)
  28. if fileExt == "" {
  29. c.JSON(nil, ecode.MCNUnknownFileExt)
  30. return
  31. }
  32. defer imageFile.Close()
  33. bs, err := ioutil.ReadAll(imageFile)
  34. if err != nil {
  35. c.JSON(nil, err)
  36. return
  37. }
  38. filetype := http.DetectContentType(bs)
  39. switch filetype {
  40. case
  41. "image/jpeg",
  42. "image/jpg",
  43. "image/png",
  44. "application/pdf":
  45. case "application/octet-stream", "application/zip":
  46. switch fileExt[1:] {
  47. case "doc":
  48. filetype = "application/doc"
  49. case "docx":
  50. filetype = "application/docx"
  51. case "docm":
  52. filetype = "application/docm"
  53. }
  54. case "application/msword":
  55. filetype = "application/doc"
  56. case "application/vnd.openxmlformats-officedocument.wordprocessingml.document":
  57. filetype = "application/docx"
  58. case "application/vnd.ms-word.document.macroEnabled.12":
  59. filetype = "application/docm"
  60. default:
  61. c.JSON(nil, ecode.MCNUnknownFileTypeErr)
  62. return
  63. }
  64. c.JSON(srv.Upload(c, "", filetype, time.Now().Unix(), bytes.NewReader(bs)))
  65. }