upload.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package http
  2. import (
  3. "context"
  4. "crypto/md5"
  5. "encoding/csv"
  6. "fmt"
  7. "net/http"
  8. "net/url"
  9. "regexp"
  10. "time"
  11. "go-common/library/log"
  12. bm "go-common/library/net/http/blademaster"
  13. )
  14. func upload(c *bm.Context) {
  15. imageFile, imageHeader, err := c.Request.FormFile("file")
  16. if err != nil {
  17. log.Error("upload err(%v)", err)
  18. httpCode(c, err)
  19. return
  20. }
  21. defer imageFile.Close()
  22. //读取前512个字节用于判断文件类型
  23. firstImageBytes := make([]byte, 512)
  24. _, err = imageFile.Read(firstImageBytes)
  25. if err != nil {
  26. log.Error("imageFile.Read error(%v)", err)
  27. httpCode(c, err)
  28. return
  29. }
  30. md5Checksum := md5.Sum(firstImageBytes)
  31. extensionMatcher := regexp.MustCompile(`\\.\\w+$`)
  32. imageName := extensionMatcher.ReplaceAllString(imageHeader.Filename, "")
  33. filetype := http.DetectContentType(firstImageBytes)
  34. var extension string
  35. switch filetype {
  36. case "image/jpeg", "image/jpg":
  37. extension = "jpg"
  38. case "image/gif":
  39. extension = "gif"
  40. case "image/png":
  41. extension = "png"
  42. case "application/pdf":
  43. extension = "pdf"
  44. default:
  45. log.Warn("unknown filetype(%s) ", filetype)
  46. return
  47. }
  48. imageName = url.PathEscape(imageName)
  49. //重新格式化文件名
  50. uploadFilePath := fmt.Sprintf("%x-%v.%v", md5Checksum, imageName, extension)
  51. local, err := creSvc.Upload(c, uploadFilePath, extension, time.Now().Unix(), imageFile)
  52. if err != nil {
  53. log.Error("creSvc.Upload error(%v)", err)
  54. httpCode(c, err)
  55. return
  56. }
  57. httpData(c, local, nil)
  58. }
  59. func annualCoins(c *bm.Context) {
  60. file, _, err := c.Request.FormFile("file")
  61. if err != nil {
  62. log.Error("upload err(%v)", err)
  63. httpCode(c, err)
  64. return
  65. }
  66. defer file.Close()
  67. reader := csv.NewReader(file)
  68. fmids := creSvc.AnnualCoins(context.Background(), reader)
  69. httpData(c, fmids, nil)
  70. }