package api import ( "arimelody-web/global" "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/") directory = filepath.Join(global.DATA_DIR, directory) 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() // TODO: generate compressed versions of image (512x512?) buffer := bufio.NewWriter(file) _, err = buffer.Write(imageData) if err != nil { return "", nil } if err := buffer.Flush(); err != nil { return "", nil } return filename, nil }