You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.2 KiB

  1. package Util
  2. import (
  3. "errors"
  4. "fmt"
  5. "io/ioutil"
  6. "os"
  7. "strings"
  8. "github.com/gabriel-vasile/mimetype"
  9. )
  10. type FileObject struct {
  11. Filepath string
  12. PublicFilepath string
  13. Mimetype string
  14. Size int64
  15. }
  16. func WriteFile(fileBytes []byte, acceptedMime string) (FileObject, error) {
  17. var (
  18. mime *mimetype.MIME
  19. mimeSplit []string
  20. file *os.File
  21. fi os.FileInfo
  22. fileObject FileObject
  23. err error
  24. )
  25. mime = mimetype.Detect(fileBytes)
  26. mimeSplit = strings.Split(mime.String(), "/")
  27. if mimeSplit[0] != acceptedMime {
  28. return fileObject, errors.New("Invalid filetype provided")
  29. }
  30. file, err = ioutil.TempFile(
  31. fmt.Sprintf(
  32. "./Frontend/public/%ss/",
  33. mimeSplit[0],
  34. ),
  35. fmt.Sprintf(
  36. "%ss-*%s",
  37. mimeSplit[0],
  38. mime.Extension(),
  39. ),
  40. )
  41. if err != nil {
  42. return fileObject, err
  43. }
  44. defer file.Close()
  45. _, err = file.Write(fileBytes)
  46. fi, err = file.Stat()
  47. if err != nil {
  48. return fileObject, err
  49. }
  50. fileObject = FileObject{
  51. Filepath: file.Name(),
  52. PublicFilepath: strings.ReplaceAll(file.Name(), "./Frontend", ""),
  53. Mimetype: mime.String(),
  54. Size: fi.Size(),
  55. }
  56. return fileObject, err
  57. }