Media upload

This commit is contained in:
cdricms
2025-01-20 10:27:54 +01:00
parent 32643be1ad
commit 8d880b8705
8 changed files with 309 additions and 4 deletions

View File

@@ -0,0 +1,73 @@
package api
import (
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"fr.latosa-escrima/api/core"
"fr.latosa-escrima/utils"
)
func HandleUploadMedia(w http.ResponseWriter, r *http.Request) {
// Parse the multipart form
err := r.ParseMultipartForm(10 << 20) // Limit file size to 10 MB
if err != nil {
core.JSONError{
Status: core.Error,
Message: err.Error(),
}.Respond(w, http.StatusRequestEntityTooLarge)
return
}
// Retrieve the file from the form
file, fileHeader, err := r.FormFile("file")
if err != nil {
core.JSONError{
Status: core.Error,
Message: err.Error(),
}.Respond(w, http.StatusBadRequest)
return
}
defer file.Close()
// Create the destination file
if !utils.DoesPathExist("media") {
fmt.Println("Creating media forlder")
err = os.MkdirAll("media", os.ModePerm)
if err != nil {
core.JSONError{
Status: core.Error,
Message: err.Error(),
}.Respond(w, http.StatusInternalServerError)
return
}
}
p := filepath.Join("media", fileHeader.Filename)
dst, err := os.Create(p)
if err != nil {
core.JSONError{
Status: core.Error,
Message: err.Error(),
}.Respond(w, http.StatusInternalServerError)
return
}
defer dst.Close()
// Copy the file content to the destination file
_, err = io.Copy(dst, file)
if err != nil {
core.JSONError{
Status: core.Error,
Message: err.Error(),
}.Respond(w, http.StatusInternalServerError)
return
}
core.JSONSuccess{
Status: core.Success,
Message: "File uploaded successfully.",
}.Respond(w, http.StatusCreated)
}

View File

@@ -0,0 +1,62 @@
package api
import (
"encoding/json"
"io"
"net/http"
"path/filepath"
"fr.latosa-escrima/api/core"
"fr.latosa-escrima/utils"
)
const MAX_SIZE_BYTES = 10 * 1024 * 1024
type FileArgs struct {
Name string `json:"name"`
Type string `json:"type"`
SizeByte int64 `json:"size"`
}
func HandleVerifyMedia(w http.ResponseWriter, r *http.Request) {
body, err := io.ReadAll(r.Body)
if err != nil {
core.JSONError{
Status: core.Error,
Message: err.Error(),
}.Respond(w, http.StatusInternalServerError)
return
}
var file FileArgs
err = json.Unmarshal(body, &file)
if err != nil {
core.JSONError{
Status: core.Error,
Message: err.Error(),
}.Respond(w, http.StatusInternalServerError)
return
}
if utils.DoesPathExist(filepath.Join("media", file.Name)) {
core.JSONError{
Status: core.Error,
Message: "File already exists.",
}.Respond(w, http.StatusInternalServerError)
return
}
if file.SizeByte > MAX_SIZE_BYTES {
core.JSONError{
Status: core.Error,
Message: "File is too big.",
}.Respond(w, http.StatusRequestEntityTooLarge)
return
}
core.JSONSuccess{
Status: core.Success,
Message: "File can be uploaded.",
}.Respond(w, http.StatusOK)
}