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.

67 lines
1.0 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. Mimetype string
  13. Size int64
  14. }
  15. func WriteFile(fileBytes []byte, acceptedMime string) (FileObject, error) {
  16. var (
  17. mime *mimetype.MIME
  18. mimeSplit []string
  19. file *os.File
  20. fi os.FileInfo
  21. fileObject FileObject
  22. err error
  23. )
  24. mime = mimetype.Detect(fileBytes)
  25. mimeSplit = strings.Split(mime.String(), "/")
  26. if mimeSplit[0] != acceptedMime {
  27. return fileObject, errors.New("Invalid filetype provided")
  28. }
  29. file, err = ioutil.TempFile(
  30. fmt.Sprintf(
  31. "./Frontend/public/%ss/",
  32. mimeSplit[0],
  33. ),
  34. fmt.Sprintf(
  35. "%ss-*%s",
  36. mimeSplit[0],
  37. mime.Extension(),
  38. ),
  39. )
  40. if err != nil {
  41. return fileObject, err
  42. }
  43. defer file.Close()
  44. _, err = file.Write(fileBytes)
  45. fi, err = file.Stat()
  46. if err != nil {
  47. return fileObject, err
  48. }
  49. fileObject = FileObject{
  50. Filepath: file.Name(),
  51. Mimetype: mime.String(),
  52. Size: fi.Size(),
  53. }
  54. return fileObject, err
  55. }