UpFile.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package controllers
  2. import (
  3. "bzd_server/conf"
  4. "bzd_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. }
  25. if _, ok := AllowExtMap[ext]; !ok {
  26. c.Ctx.WriteString("后缀名不符合上传要求")
  27. return
  28. }
  29. //创建目录
  30. uploadDir := conf.Oss_file // + time.Now().Format("2006/01/02/")
  31. err := os.MkdirAll(uploadDir, 777)
  32. if err != nil {
  33. c.Ctx.WriteString(fmt.Sprintf("%v", err))
  34. return
  35. }
  36. //构造文件名称
  37. rand.Seed(time.Now().UnixNano())
  38. randNum := fmt.Sprintf("%d", rand.Intn(9999)+1000)
  39. hashName := md5.Sum([]byte(time.Now().Format("2006_01_02_15_04_05_") + randNum))
  40. fileName := fmt.Sprintf("%x", hashName) + ext
  41. //this.Ctx.WriteString( fileName )
  42. fpath := uploadDir + fileName
  43. println(fpath)
  44. defer f.Close() //关闭上传的文件,不然的话会出现临时文件不能清除的情况
  45. err = c.SaveToFile("file", fpath)
  46. if err != nil {
  47. c.Ctx.WriteString(fmt.Sprintf("%v", err))
  48. }
  49. c.Ctx.WriteString("{\n \"code\": 0\n ,\"msg\": \"ok!\"\n ,\"data\": {\n \"src\": \"" + conf.Oss + fileName + "\"\n }\n} ")
  50. }
  51. // 列表 -
  52. func (c *UpFileController) ConfigUpFileToken() {
  53. // 验证登录 User_r, User_x
  54. //b_, User_r, _ := lib.Verification(c.Ctx.GetCookie("User_tokey"), c.GetString("User_tokey"))
  55. //if !b_ {
  56. // c.Data["json"] = lib.JSONS{Code: 302, Msg: "请重新登录!"}
  57. // c.ServeJSON()
  58. // return
  59. //}
  60. c.Data["json"] = lib.JSONS{Code: 200, Msg: "ok!", Data: lib.UploadToken(c.GetString("T_suffix"))}
  61. c.ServeJSON()
  62. return
  63. }