file.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. package controller
  2. import (
  3. "encoding/json"
  4. "github.com/gin-gonic/gin"
  5. "iot_manager_service/app/file/model"
  6. "iot_manager_service/app/file/service"
  7. "iot_manager_service/util/cache"
  8. "iot_manager_service/util/common"
  9. "iot_manager_service/util/token"
  10. "net/http"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "strconv"
  15. "time"
  16. )
  17. var FileController = new(file)
  18. type file struct{}
  19. func (f *file) Distribute(c *gin.Context) {
  20. //获取当前用户
  21. header := c.GetHeader("Authorization")
  22. claims, _ := token.JwtClaims.ParseJwtToken(header)
  23. nowUser, _ := cache.GetToken(claims.ID)
  24. //TODO:校验签名 如果成功则上传否则不上传
  25. formFile, err := c.FormFile("file")
  26. if err != nil {
  27. c.JSON(http.StatusOK, common.ParamsInvalidResponse("获取文件数据失败", nil))
  28. return
  29. }
  30. //获取后缀
  31. sufx := path.Ext(formFile.Filename)
  32. //利用时间戳生成文件名
  33. fileNameInt := time.Now().Unix()
  34. fileNameStr := strconv.FormatInt(fileNameInt, 10)
  35. //新的文件名
  36. newfileName := fileNameStr + sufx
  37. _, err = os.Stat("uploadfiles")
  38. if os.IsNotExist(err) {
  39. os.Mkdir("./uploadfiles", os.ModePerm)
  40. }
  41. //保存文件
  42. filePath := filepath.Join("uploadfiles", "/", newfileName)
  43. c.SaveUploadedFile(formFile, filePath)
  44. //获取另外一个参数
  45. str := c.Request.FormValue("req")
  46. userFile := model.ReqUserFile{}
  47. json.Unmarshal([]byte(str), &userFile)
  48. savePath := "/uploadfiles/" + newfileName
  49. distribute := service.FileService.Distribute(formFile.Filename, savePath, &userFile, nowUser.User.ID)
  50. c.JSON(http.StatusOK, distribute)
  51. }
  52. func (f *file) GetUserFiles(c *gin.Context) {
  53. header := c.GetHeader("Authorization")
  54. claims, _ := token.JwtClaims.ParseJwtToken(header)
  55. files := service.FileService.GetUserFiles(claims.ID)
  56. c.JSON(http.StatusOK, files)
  57. }