turns out rewriting all of your database code takes a while
This commit is contained in:
parent
1998a36d6d
commit
965d6f5c3e
30 changed files with 947 additions and 1036 deletions
49
api/uploads.go
Normal file
49
api/uploads.go
Normal file
|
@ -0,0 +1,49 @@
|
|||
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()
|
||||
|
||||
buffer := bufio.NewWriter(file)
|
||||
_, err = buffer.Write(imageData)
|
||||
if err != nil {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
if err := buffer.Flush(); err != nil {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
return filename, nil
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue