UpFile.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package controllers
  2. import (
  3. "ColdVerify_server/conf"
  4. "ColdVerify_server/lib"
  5. "crypto/md5"
  6. "fmt"
  7. beego "github.com/beego/beego/v2/server/web"
  8. "math/rand"
  9. "os"
  10. "path"
  11. "time"
  12. )
  13. type UpFileController struct {
  14. beego.Controller
  15. }
  16. func (c *UpFileController) UpFile() {
  17. f, h, _ := c.GetFile("file") //获取上传的文件
  18. ext := path.Ext(h.Filename)
  19. //验证后缀名是否符合要求
  20. var AllowExtMap map[string]bool = map[string]bool{
  21. ".jpg": true,
  22. ".jpeg": true,
  23. ".png": true,
  24. ".pdf": true,
  25. }
  26. if _, ok := AllowExtMap[ext]; !ok {
  27. c.Ctx.WriteString("后缀名不符合上传要求")
  28. return
  29. }
  30. //创建目录
  31. uploadDir := conf.Oss_file // + time.Now().Format("2006/01/02/")
  32. err := os.MkdirAll(uploadDir, 777)
  33. if err != nil {
  34. c.Ctx.WriteString(fmt.Sprintf("%v", err))
  35. return
  36. }
  37. //构造文件名称
  38. rand.Seed(time.Now().UnixNano())
  39. randNum := fmt.Sprintf("%d", rand.Intn(9999)+1000)
  40. hashName := md5.Sum([]byte(time.Now().Format("2006_01_02_15_04_05_") + randNum))
  41. fileName := fmt.Sprintf("%x", hashName) + ext
  42. //this.Ctx.WriteString( fileName )
  43. fpath := uploadDir + fileName
  44. println(fpath)
  45. defer f.Close() //关闭上传的文件,不然的话会出现临时文件不能清除的情况
  46. err = c.SaveToFile("file", fpath)
  47. if err != nil {
  48. c.Ctx.WriteString(fmt.Sprintf("%v", err))
  49. }
  50. c.Ctx.WriteString("{\n \"code\": 0\n ,\"msg\": \"ok!\"\n ,\"data\": {\n \"src\": \"" + conf.Oss + fileName + "\"\n }\n} ")
  51. }
  52. // 列表 -
  53. func (c *UpFileController) ConfigUpFileToken() {
  54. // 验证登录 User_r, User_x
  55. //b_, User_r, _ := Account.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  56. //if !b_ {
  57. // c.Data["json"] = lib.JSONS{Code: 201, Msg: "请重新登录!"}
  58. // c.ServeJSON()
  59. // return
  60. //}
  61. c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!", Data: lib.UploadToken(c.GetString("T_suffix"))}
  62. c.ServeJSON()
  63. return
  64. }