Added cleanup logic.

This commit is contained in:
2025-08-07 22:25:02 +02:00
parent afccf236fc
commit 716c6730b5
9 changed files with 115 additions and 16 deletions

31
controllers/download.go Normal file
View File

@@ -0,0 +1,31 @@
package controllers
import (
"net/http"
"os"
"path/filepath"
"github.com/gin-gonic/gin"
)
func HandleFileDownload(c *gin.Context) {
fileID, filename := c.Param("fileID"), c.Param("filename")
if fileID == "" || filename == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "File ID and filename are required"})
return
}
filePath := filepath.Join("./uploads", fileID, filename)
if _, err := os.Stat(filePath); os.IsNotExist(err) {
c.JSON(http.StatusNotFound, gin.H{"error": "File not found"})
return
}
c.Header("Content-Description", "File Transfer")
c.Header("Content-Transfer-Encoding", "binary")
c.Header("Content-Disposition", "attachment; filename="+filename)
c.Header("Content-Type", "application/octet-stream")
c.File(filePath)
}

16
controllers/index.go Normal file
View File

@@ -0,0 +1,16 @@
package controllers
import (
"net/http"
"os"
"github.com/gin-gonic/gin"
)
func HandleIndex(c *gin.Context) {
baseURL := os.Getenv("BASE_URL")
if baseURL == "" {
baseURL = "http://localhost:8080"
}
c.HTML(http.StatusOK, "index.html", gin.H{"BaseURL": baseURL})
}

64
controllers/upload.go Normal file
View File

@@ -0,0 +1,64 @@
package controllers
import (
"crypto/rand"
"encoding/hex"
"io"
"net/http"
"os"
"path/filepath"
"github.com/gin-gonic/gin"
)
func generateID() (string, error) {
bytes := make([]byte, 16)
_, err := rand.Read(bytes)
return hex.EncodeToString(bytes), err
}
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()
fileID, err := generateID()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate file ID"})
return
}
fileDir := filepath.Join("./uploads", fileID)
if err := os.MkdirAll(fileDir, 0755); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create file directory"})
return
}
out, err := os.Create(filepath.Join(fileDir, header.Filename))
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create file"})
return
}
defer out.Close()
if _, err = io.Copy(out, file); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to save file"})
return
}
baseURL := os.Getenv("BASE_URL")
if baseURL == "" {
baseURL = "http://localhost:8080"
}
c.JSON(http.StatusOK, gin.H{
"message": "File uploaded successfully",
"id": fileID,
"filename": header.Filename,
"size": header.Size,
"url": baseURL + "/files/" + fileID + "/" + header.Filename,
})
}