1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071 |
- package handler
- import (
- "net/http"
- "os"
- "path/filepath"
- "github.com/gin-gonic/gin"
- "github.com/jianboy/filecloud/internal/database"
- "github.com/jianboy/filecloud/internal/model"
- )
- // @Summary Upload a file
- // @Description Upload a file to the cloud storage
- // @Tags files
- // @Accept multipart/form-data
- // @Produce json
- // @Param file formData file true "File to upload"
- // @Success 200 {object} model.File
- // @Router /api/files [post]
- func UploadFile(c *gin.Context) {
- file, err := c.FormFile("file")
- if err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
- return
- }
- // Create public directory if it doesn't exist
- publicDir := filepath.Join("public", "uploads")
- if err := os.MkdirAll(publicDir, 0755); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
- return
- }
- // Save the file
- filePath := filepath.Join(publicDir, file.Filename)
- if err := c.SaveUploadedFile(file, filePath); err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
- return
- }
- // Create file record in database
- fileRecord := model.File{
- Name: file.Filename,
- Path: filePath,
- Size: file.Size,
- Type: file.Header.Get("Content-Type"),
- }
- if err := database.DB.Create(&fileRecord).Error; err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
- return
- }
- c.JSON(http.StatusOK, fileRecord)
- }
- // @Summary List all files
- // @Description Get a list of all files in the cloud storage
- // @Tags files
- // @Produce json
- // @Success 200 {array} model.File
- // @Router /api/files [get]
- func ListFiles(c *gin.Context) {
- var files []model.File
- if err := database.DB.Find(&files).Error; err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
- return
- }
- c.JSON(http.StatusOK, files)
- }
|