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)
}