|
|
@@ -0,0 +1,87 @@
|
|
|
+package router
|
|
|
+
|
|
|
+import (
|
|
|
+ "file/entity"
|
|
|
+ "file/gin/service"
|
|
|
+ "file/util"
|
|
|
+ "fmt"
|
|
|
+ "github.com/gin-gonic/gin"
|
|
|
+ "net/http"
|
|
|
+ "strings"
|
|
|
+)
|
|
|
+
|
|
|
+func UploadFile(c *gin.Context) {
|
|
|
+ // 获取上传的所有文件
|
|
|
+ form, err := c.MultipartForm()
|
|
|
+ if err != nil {
|
|
|
+ c.JSON(http.StatusBadRequest, CreateResultError(400, "Failed to parse form"))
|
|
|
+ return
|
|
|
+ }
|
|
|
+
|
|
|
+ // 获取所有上传的文件
|
|
|
+ files := form.File["files[]"]
|
|
|
+ if len(files) == 0 {
|
|
|
+ c.JSON(http.StatusBadRequest, CreateResultError(400, "No files uploaded"))
|
|
|
+ return
|
|
|
+ }
|
|
|
+ //获取用户名称
|
|
|
+ cookie, err := c.Cookie("token")
|
|
|
+ if err != nil {
|
|
|
+ c.JSON(http.StatusUnauthorized, CreateResultError(401, "Failed to get token"))
|
|
|
+ return
|
|
|
+ }
|
|
|
+ claims, err := util.ValidateTokenToMyClaims(cookie)
|
|
|
+ if err != nil {
|
|
|
+ c.JSON(http.StatusUnauthorized, CreateResultError(401, err.Error()))
|
|
|
+ return
|
|
|
+ }
|
|
|
+ fmt.Println(claims.Id)
|
|
|
+ user, err := service.UserDao{}.GetById(claims.Id)
|
|
|
+ if err != nil {
|
|
|
+ c.JSON(http.StatusInternalServerError, CreateResultError(500, "Failed to get user"))
|
|
|
+ return
|
|
|
+ }
|
|
|
+
|
|
|
+ // 遍历文件并保存
|
|
|
+ for _, file := range files {
|
|
|
+ // 获取文件路径
|
|
|
+ pars := strings.Split(file.Header.Get("Content-Disposition"), ";")
|
|
|
+ path := ""
|
|
|
+ for i := range pars {
|
|
|
+ split := strings.Split(pars[i], "=")
|
|
|
+ if len(split) > 1 && strings.TrimSpace(split[0]) == "filename" {
|
|
|
+ path = strings.Trim(split[1], "\"")
|
|
|
+ break
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ fmt.Println(file.Filename, file.Size, path)
|
|
|
+ // 创建目录
|
|
|
+ dst := fmt.Sprintf("./uploads/%s/%s", user.Username, path)
|
|
|
+ fmt.Println("==> ", dst)
|
|
|
+ err := c.SaveUploadedFile(file, dst)
|
|
|
+ if err != nil {
|
|
|
+ c.JSON(http.StatusInternalServerError, CreateResultError(400, "Failed to save file"))
|
|
|
+ return
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // 返回成功消息
|
|
|
+ c.JSON(http.StatusOK, CreateResult())
|
|
|
+}
|
|
|
+func computeFile(name, path, fileType string, size int64) entity.File {
|
|
|
+ return entity.File{
|
|
|
+ Name: name,
|
|
|
+ Url: path,
|
|
|
+ Size: size,
|
|
|
+ Type: fileType,
|
|
|
+ MD5: "",
|
|
|
+ ParentId: "",
|
|
|
+ Extension: "",
|
|
|
+ Access: "",
|
|
|
+ CreateUser: 0,
|
|
|
+ CreateTime: 0,
|
|
|
+ UpdateTime: 0,
|
|
|
+ }
|
|
|
+
|
|
|
+}
|