FileRouter.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package router
  2. import (
  3. "file/entity"
  4. "file/gin/service"
  5. "file/util"
  6. "fmt"
  7. "github.com/gin-gonic/gin"
  8. "net/http"
  9. "strings"
  10. )
  11. func UploadFile(c *gin.Context) {
  12. // 获取上传的所有文件
  13. form, err := c.MultipartForm()
  14. if err != nil {
  15. c.JSON(http.StatusBadRequest, CreateResultError(400, "Failed to parse form"))
  16. return
  17. }
  18. // 获取所有上传的文件
  19. files := form.File["files[]"]
  20. if len(files) == 0 {
  21. c.JSON(http.StatusBadRequest, CreateResultError(400, "No files uploaded"))
  22. return
  23. }
  24. //获取用户名称
  25. cookie, err := c.Cookie("token")
  26. if err != nil {
  27. c.JSON(http.StatusUnauthorized, CreateResultError(401, "Failed to get token"))
  28. return
  29. }
  30. claims, err := util.ValidateTokenToMyClaims(cookie)
  31. if err != nil {
  32. c.JSON(http.StatusUnauthorized, CreateResultError(401, err.Error()))
  33. return
  34. }
  35. fmt.Println(claims.Id)
  36. user, err := service.UserDao{}.GetById(claims.Id)
  37. if err != nil {
  38. c.JSON(http.StatusInternalServerError, CreateResultError(500, "Failed to get user"))
  39. return
  40. }
  41. // 遍历文件并保存
  42. for _, file := range files {
  43. // 获取文件路径
  44. pars := strings.Split(file.Header.Get("Content-Disposition"), ";")
  45. path := ""
  46. for i := range pars {
  47. split := strings.Split(pars[i], "=")
  48. if len(split) > 1 && strings.TrimSpace(split[0]) == "filename" {
  49. path = strings.Trim(split[1], "\"")
  50. break
  51. }
  52. }
  53. fmt.Println(file.Filename, file.Size, path)
  54. // 创建目录
  55. dst := fmt.Sprintf("./uploads/%s/%s", user.Username, path)
  56. fmt.Println("==> ", dst)
  57. err := c.SaveUploadedFile(file, dst)
  58. if err != nil {
  59. c.JSON(http.StatusInternalServerError, CreateResultError(400, "Failed to save file"))
  60. return
  61. }
  62. }
  63. // 返回成功消息
  64. c.JSON(http.StatusOK, CreateResult())
  65. }
  66. func computeFile(name, path, fileType string, size int64) entity.File {
  67. return entity.File{
  68. Name: name,
  69. Url: path,
  70. Size: size,
  71. Type: fileType,
  72. MD5: "",
  73. ParentId: "",
  74. Extension: "",
  75. Access: "",
  76. CreateUser: 0,
  77. CreateTime: 0,
  78. UpdateTime: 0,
  79. }
  80. }