file.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package repositories
  2. import (
  3. "mime/multipart"
  4. "os"
  5. "github.com/disintegration/imaging"
  6. "github.com/gofiber/fiber/v2"
  7. )
  8. const (
  9. uploadPath = "../../web/public"
  10. resizeWidth = 1000
  11. resizeHeight = 800
  12. )
  13. type FileRepository struct{}
  14. func InitFileRepository() *FileRepository {
  15. return &FileRepository{}
  16. }
  17. func (r FileRepository) Save(fctx *fiber.Ctx, header *multipart.FileHeader, path string) error {
  18. fullPath := getFullPath(path)
  19. if err := fctx.SaveFile(header, fullPath); err != nil {
  20. return err
  21. }
  22. // Resize image
  23. src, err := imaging.Open(fullPath)
  24. if err != nil {
  25. return err
  26. }
  27. origHeight := src.Bounds().Size().Y
  28. origWidth := src.Bounds().Size().X
  29. var newHeight, newWidth int
  30. if origWidth > origHeight {
  31. newWidth = resizeWidth
  32. } else {
  33. newHeight = resizeHeight
  34. }
  35. dst := imaging.Resize(src, newWidth, newHeight, imaging.Lanczos)
  36. if err = imaging.Save(dst, fullPath); err != nil {
  37. return err
  38. }
  39. return nil
  40. }
  41. func (r FileRepository) Delete(path string) error {
  42. return os.RemoveAll(getFullPath(path))
  43. }
  44. func getFullPath(path string) string {
  45. return uploadPath + path
  46. }