upload.go 1.4 KB

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