filesystem.go 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package filesystem
  2. import (
  3. "io"
  4. "os"
  5. "path/filepath"
  6. "github.com/qor5/admin/media"
  7. )
  8. var _ media.Media = &FileSystem{}
  9. // FileSystem defined a media library storage using file system
  10. type FileSystem struct {
  11. media.Base
  12. }
  13. // GetFullPath return full file path from a relative file path
  14. func (f FileSystem) GetFullPath(url string, option *media.Option) (path string, err error) {
  15. if option != nil && option.Get("path") != "" {
  16. path = filepath.Join(option.Get("path"), url)
  17. } else {
  18. path = filepath.Join("./public", url)
  19. }
  20. dir := filepath.Dir(path)
  21. if _, err := os.Stat(dir); os.IsNotExist(err) {
  22. err = os.MkdirAll(dir, os.ModePerm)
  23. }
  24. return
  25. }
  26. // Store save reader's context with name
  27. func (f FileSystem) Store(name string, option *media.Option, reader io.Reader) (err error) {
  28. if fullpath, err := f.GetFullPath(name, option); err == nil {
  29. if dst, err := os.Create(fullpath); err == nil {
  30. _, err = io.Copy(dst, reader)
  31. }
  32. }
  33. return err
  34. }
  35. // Retrieve retrieve file content with url
  36. func (f FileSystem) Retrieve(url string) (media.FileInterface, error) {
  37. if fullpath, err := f.GetFullPath(url, nil); err == nil {
  38. return os.Open(fullpath)
  39. }
  40. return nil, os.ErrNotExist
  41. }