minio.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package handlers
  2. import (
  3. "easydo-echo_win7/models"
  4. "easydo-echo_win7/services"
  5. "easydo-echo_win7/utils"
  6. "fmt"
  7. "net/http"
  8. "path/filepath"
  9. // "strings"
  10. "easydo-echo_win7/middleware"
  11. "github.com/google/uuid"
  12. "github.com/labstack/echo/v4"
  13. )
  14. func Add_minio_to_routes(e *echo.Echo) {
  15. group := e.Group("/file")
  16. group.Use(middleware.AuthMiddleware)
  17. group.POST("/upload", fileUpload)
  18. group.POST("/remove", fileRemove)
  19. }
  20. // 响应结构体
  21. type UploadResponse struct {
  22. Code int `json:"code"`
  23. Message string `json:"message"`
  24. Expands map[string]interface{} `json:"expands,omitempty"`
  25. }
  26. // UploadHandler 是您的主要处理函数
  27. func fileUpload(c echo.Context) error {
  28. // 1. 从form-data中获取文件
  29. file, err := c.FormFile("file")
  30. if err != nil {
  31. return c.JSON(http.StatusBadRequest, utils.ErrorResponse("无法获取上传的文件,请检查字段名是否为'file'", ""))
  32. }
  33. // 2. 打开上传的文件
  34. src, err := file.Open()
  35. if err != nil {
  36. return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("无法打开上传的文件", ""))
  37. }
  38. defer src.Close()
  39. // 3. 生成唯一对象名并上传到MinIO
  40. objectName := generateUUIDFileName(file.Filename)
  41. // 上传到MinIO[citation:2]
  42. filePath, err := services.MinioClient.UploadFile(services.BucketName, src, objectName)
  43. if err != nil {
  44. return c.JSON(http.StatusInternalServerError, utils.ErrorResponse(fmt.Sprintf("上传到MinIO失败: %v", err), ""))
  45. }
  46. // 构建成功响应
  47. return c.JSON(http.StatusOK, UploadResponse{
  48. Code: 200,
  49. Message: "success",
  50. Expands: map[string]interface{}{
  51. "file": filePath,
  52. },
  53. })
  54. }
  55. // 生成UUID的辅助函数
  56. func generateUUIDFileName(filename string) string {
  57. fullExt := filepath.Ext(filename)
  58. uuid := uuid.New()
  59. return uuid.String() + fullExt
  60. }
  61. func fileRemove(c echo.Context) error {
  62. file := new(models.MinioFile)
  63. if err := c.Bind(file); err != nil {
  64. return c.JSON(http.StatusOK, nil)
  65. }
  66. // file_path := *file.Path
  67. // bucketName := strings.Split(file_path[1:], "/")[0]
  68. // objectName := file_path[1+len(bucketName)+1:]
  69. // services.MinioClient.RemoveFile(bucketName,objectName)
  70. if file.ID != nil {
  71. err := services.JdbcClient.JdbcRemoveById(file)
  72. if err != nil {
  73. utils.PrintSqlErr(err)
  74. return c.JSON(http.StatusInternalServerError, utils.ErrorResponse("系统错误", ""))
  75. }
  76. }
  77. return c.JSON(http.StatusOK, file)
  78. }