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