upbfs.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package service
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/md5"
  6. "encoding/hex"
  7. "io"
  8. "net/http"
  9. "go-common/app/admin/main/creative/model/bfs"
  10. "go-common/library/ecode"
  11. "go-common/library/log"
  12. )
  13. // Upload to bfs
  14. func (s *Service) Upload(c context.Context, fileName string, fileType string, timing int64, body []byte) (location string, err error) {
  15. if len(body) == 0 {
  16. err = ecode.FileNotExists
  17. return
  18. }
  19. if len(body) > s.conf.Bfs.MaxFileSize {
  20. err = ecode.FileTooLarge
  21. return
  22. }
  23. if location, err = s.dao.Upload(c, fileName, fileType, timing, body, s.conf.Bfs); err != nil {
  24. log.Error("s.upload.Upload() error(%v)", err)
  25. }
  26. return
  27. }
  28. // ParseFile analyses file info
  29. func (s *Service) ParseFile(c context.Context, content []byte) (file *bfs.FileInfo, err error) {
  30. fType := http.DetectContentType(content)
  31. // file md5
  32. md5hash := md5.New()
  33. if _, err = io.Copy(md5hash, bytes.NewReader(content)); err != nil {
  34. log.Error("resource uploadFile.Copy error(%v)", err)
  35. return
  36. }
  37. md5 := md5hash.Sum(nil)
  38. fMd5 := hex.EncodeToString(md5[:])
  39. file = &bfs.FileInfo{
  40. Md5: fMd5,
  41. Type: fType,
  42. Size: int64(len(content)),
  43. }
  44. return
  45. }