package controller import ( "encoding/json" "github.com/gin-gonic/gin" "iot_manager_service/app/file/model" "iot_manager_service/app/file/service" "iot_manager_service/util/cache" "iot_manager_service/util/common" "iot_manager_service/util/token" "net/http" "os" "path" "path/filepath" "strconv" "time" ) var FileController = new(file) type file struct{} func (f *file) Distribute(c *gin.Context) { //获取当前用户 header := c.GetHeader("Authorization") claims, _ := token.JwtClaims.ParseJwtToken(header) nowUser, _ := cache.GetToken(claims.ID) //TODO:校验签名 如果成功则上传否则不上传 formFile, err := c.FormFile("file") if err != nil { c.JSON(http.StatusOK, common.ParamsInvalidResponse("获取文件数据失败", nil)) return } //获取后缀 sufx := path.Ext(formFile.Filename) //利用时间戳生成文件名 fileNameInt := time.Now().Unix() fileNameStr := strconv.FormatInt(fileNameInt, 10) //新的文件名 newfileName := fileNameStr + sufx _, err = os.Stat("uploadfiles") if os.IsNotExist(err) { os.Mkdir("./uploadfiles", os.ModePerm) } //保存文件 filePath := filepath.Join("uploadfiles", "/", newfileName) c.SaveUploadedFile(formFile, filePath) //获取另外一个参数 str := c.Request.FormValue("req") userFile := model.ReqUserFile{} json.Unmarshal([]byte(str), &userFile) savePath := "/uploadfiles/" + newfileName distribute := service.FileService.Distribute(formFile.Filename, savePath, &userFile, nowUser.User.ID) c.JSON(http.StatusOK, distribute) } func (f *file) GetUserFiles(c *gin.Context) { header := c.GetHeader("Authorization") claims, _ := token.JwtClaims.ParseJwtToken(header) files := service.FileService.GetUserFiles(claims.ID) c.JSON(http.StatusOK, files) }