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

package Util
import (
"errors"
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/gabriel-vasile/mimetype"
)
type FileObject struct {
Filepath string
PublicFilepath string
Mimetype string
Size int64
}
func WriteFile(fileBytes []byte, acceptedMime string) (FileObject, error) {
var (
mime *mimetype.MIME
mimeSplit []string
file *os.File
fi os.FileInfo
fileObject FileObject
err error
)
mime = mimetype.Detect(fileBytes)
mimeSplit = strings.Split(mime.String(), "/")
if mimeSplit[0] != acceptedMime {
return fileObject, errors.New("Invalid filetype provided")
}
file, err = ioutil.TempFile(
fmt.Sprintf(
"./Frontend/public/%ss/",
mimeSplit[0],
),
fmt.Sprintf(
"%ss-*%s",
mimeSplit[0],
mime.Extension(),
),
)
if err != nil {
return fileObject, err
}
defer file.Close()
_, err = file.Write(fileBytes)
fi, err = file.Stat()
if err != nil {
return fileObject, err
}
fileObject = FileObject{
Filepath: file.Name(),
PublicFilepath: strings.ReplaceAll(file.Name(), "./Frontend", ""),
Mimetype: mime.String(),
Size: fi.Size(),
}
return fileObject, err
}