local.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. package upload
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "github.com/gogf/gf/v2/frame/g"
  7. "github.com/gogf/gf/v2/net/ghttp"
  8. "github.com/tiger1103/gfast/v3/api/v1/system"
  9. "github.com/tiger1103/gfast/v3/internal/app/common/consts"
  10. "strings"
  11. "time"
  12. )
  13. type Local struct {
  14. }
  15. func (s *Local) Upload(ctx context.Context, file *ghttp.UploadFile) (result system.UploadResponse, err error) {
  16. if file == nil {
  17. err = errors.New("文件必须!")
  18. return
  19. }
  20. r := g.RequestFromCtx(ctx)
  21. urlPerfix := fmt.Sprintf("http://%s/", r.Host)
  22. p := strings.Trim(consts.UploadPath, "/")
  23. sp := s.getStaticPath(ctx)
  24. if sp != "" {
  25. sp = strings.Trim(sp, "/")
  26. }
  27. nowData := time.Now().Format("2006-01-02")
  28. // 包含静态文件夹的路径
  29. fullDirPath := sp + "/" + p + "/" + nowData
  30. fileName, err := file.Save(fullDirPath, true)
  31. if err != nil {
  32. return
  33. }
  34. // 不含静态文件夹的路径
  35. fullPath := p + "/" + nowData + "/" + fileName
  36. result = system.UploadResponse{
  37. Size: file.Size,
  38. Path: fullPath,
  39. FullPath: urlPerfix + fullPath,
  40. Name: file.Filename,
  41. Type: file.Header.Get("Content-type"),
  42. }
  43. return
  44. }
  45. // 静态文件夹目录
  46. func (s *Local) getStaticPath(ctx context.Context) string {
  47. value, _ := g.Cfg().Get(ctx, "server.serverRoot")
  48. if !value.IsEmpty() {
  49. return value.String()
  50. }
  51. return ""
  52. }