Files
fitra-backend/endpoints/upload.go
2025-08-07 21:45:04 +02:00

45 lines
984 B
Go

package endpoints
import (
"io"
"net/http"
"os"
"path/filepath"
"github.com/gin-gonic/gin"
)
func HandleFileUpload(c *gin.Context) {
file, header, err := c.Request.FormFile("file")
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "No file provided"})
return
}
defer file.Close()
uploadsDir := "./uploads"
if err := os.MkdirAll(uploadsDir, 0755); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create uploads directory"})
return
}
dst := filepath.Join(uploadsDir, header.Filename)
out, err := os.Create(dst)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create file"})
return
}
defer out.Close()
_, err = io.Copy(out, file)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save file"})
return
}
c.JSON(http.StatusOK, gin.H{
"message": "File uploaded successfully",
"filename": header.Filename,
"size": header.Size,
})
}