123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- 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.GetNowUser(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)
- }
- // 转发文件
- func (f *file) ForwardingFile(c *gin.Context) {
- fileid := c.Query("fileid")
- header := c.GetHeader("Authorization")
- claims, _ := token.JwtClaims.ParseJwtToken(header)
- requsers := model.ReqUsers{}
- 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.UsersId)
- 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)
- }
|