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) nowSysUser, _ := cache.GetNowSysUser(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.ReqSysUserFile{} json.Unmarshal([]byte(str), &userFile) savePath := "uploadfiles/" + newfileName distribute := service.FileService.Distribute(formFile.Filename, savePath, &userFile, nowSysUser.ID) c.JSON(http.StatusOK, distribute) } func (f *file) GetSysUserFiles(c *gin.Context) { header := c.GetHeader("Authorization") claims, _ := token.JwtClaims.ParseJwtToken(header) var search model.SearchSysUserFiles err := c.ShouldBindJSON(&search) if err != nil { c.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil)) return } files := service.FileService.GetSysUserFiles(claims.ID, search) c.JSON(http.StatusOK, files) } // 转发文件 func (f *file) ForwardingFile(c *gin.Context) { fileid := c.Query("fileId") header := c.GetHeader("Authorization") claims, _ := token.JwtClaims.ParseJwtToken(header) requsers := model.ReqSysUsers{} if err := c.ShouldBindJSON(&requsers); err != nil { c.JSON(http.StatusOK, common.ParamsInvalidResponse(err.Error(), nil)) return } uid, _ := strconv.Atoi(claims.ID) fid, _ := strconv.Atoi(fileid) forwardingFile := service.FileService.ForwardingFile(uid, fid, requsers.SysUsersId) c.JSON(http.StatusOK, forwardingFile) } // 查看文件 func (f *file) ViewFile(c *gin.Context) { fileId := c.Query("fileId") service.FileService.GetFile(fileId, c) } // 下载文件 func (f *file) DownloadFile(c *gin.Context) { fileid := c.Query("fileId") service.FileService.GetFile(fileid, c) }