2024-09-01 03:43:32 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"encoding/base64"
|
|
|
|
"errors"
|
|
|
|
"fmt"
|
|
|
|
"os"
|
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
|
|
|
func HandleImageUpload(data *string, directory string, filename string) (string, error) {
|
|
|
|
split := strings.Split(*data, ";base64,")
|
|
|
|
header := split[0]
|
|
|
|
imageData, err := base64.StdEncoding.DecodeString(split[1])
|
|
|
|
ext, _ := strings.CutPrefix(header, "data:image/")
|
|
|
|
|
|
|
|
switch ext {
|
|
|
|
case "png":
|
|
|
|
case "jpg":
|
|
|
|
case "jpeg":
|
|
|
|
default:
|
|
|
|
return "", errors.New("Invalid image type. Allowed: .png, .jpg, .jpeg")
|
|
|
|
}
|
|
|
|
filename = fmt.Sprintf("%s.%s", filename, ext)
|
|
|
|
|
|
|
|
// ensure directory exists
|
|
|
|
os.MkdirAll(directory, os.ModePerm)
|
|
|
|
|
|
|
|
imagePath := filepath.Join(directory, filename)
|
|
|
|
file, err := os.Create(imagePath)
|
|
|
|
if err != nil {
|
|
|
|
return "", err
|
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
|
2024-09-03 07:07:45 +00:00
|
|
|
// TODO: generate compressed versions of image (512x512?)
|
|
|
|
|
2024-09-01 03:43:32 +00:00
|
|
|
buffer := bufio.NewWriter(file)
|
|
|
|
_, err = buffer.Write(imageData)
|
|
|
|
if err != nil {
|
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := buffer.Flush(); err != nil {
|
|
|
|
return "", nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return filename, nil
|
|
|
|
}
|