2024-09-01 03:43:32 +00:00
|
|
|
package api
|
|
|
|
|
|
|
|
import (
|
2024-11-10 00:37:01 +00:00
|
|
|
"arimelody-web/global"
|
2024-09-01 03:43:32 +00:00
|
|
|
"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/")
|
2024-11-10 05:34:04 +00:00
|
|
|
directory = filepath.Join(global.Config.DataDirectory, directory)
|
2024-09-01 03:43:32 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|