file.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package handler
  2. import (
  3. "net/http"
  4. "os"
  5. "path/filepath"
  6. "github.com/gin-gonic/gin"
  7. "github.com/jianboy/filecloud/internal/database"
  8. "github.com/jianboy/filecloud/internal/model"
  9. )
  10. // @Summary Upload a file
  11. // @Description Upload a file to the cloud storage
  12. // @Tags files
  13. // @Accept multipart/form-data
  14. // @Produce json
  15. // @Param file formData file true "File to upload"
  16. // @Success 200 {object} model.File
  17. // @Router /api/files [post]
  18. func UploadFile(c *gin.Context) {
  19. file, err := c.FormFile("file")
  20. if err != nil {
  21. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  22. return
  23. }
  24. // Create public directory if it doesn't exist
  25. publicDir := filepath.Join("public", "uploads")
  26. if err := os.MkdirAll(publicDir, 0755); err != nil {
  27. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  28. return
  29. }
  30. // Save the file
  31. filePath := filepath.Join(publicDir, file.Filename)
  32. if err := c.SaveUploadedFile(file, filePath); err != nil {
  33. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  34. return
  35. }
  36. // Create file record in database
  37. fileRecord := model.File{
  38. Name: file.Filename,
  39. Path: filePath,
  40. Size: file.Size,
  41. Type: file.Header.Get("Content-Type"),
  42. }
  43. if err := database.DB.Create(&fileRecord).Error; err != nil {
  44. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  45. return
  46. }
  47. c.JSON(http.StatusOK, fileRecord)
  48. }
  49. // @Summary List all files
  50. // @Description Get a list of all files in the cloud storage
  51. // @Tags files
  52. // @Produce json
  53. // @Success 200 {array} model.File
  54. // @Router /api/files [get]
  55. func ListFiles(c *gin.Context) {
  56. var files []model.File
  57. if err := database.DB.Find(&files).Error; err != nil {
  58. c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
  59. return
  60. }
  61. c.JSON(http.StatusOK, files)
  62. }