file.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "os"
  6. "path"
  7. "regexp"
  8. "sparrow/pkg/server"
  9. "sparrow/pkg/utils"
  10. "strconv"
  11. "github.com/kataras/iris"
  12. )
  13. func registerRouter(app *iris.Application, fc *FileAccess) {
  14. app.Post("/upload_file", iris.LimitRequestBodySize(int64(*conMaxSize)),
  15. func(ctx iris.Context) {
  16. file, info, err := ctx.FormFile("file")
  17. if err != nil {
  18. server.Log.Error(err)
  19. ctx.JSON(map[string]interface{}{
  20. "code": -1,
  21. "message": "无法找到文件或文件大小超过限制(" + strconv.Itoa(*conMaxSize) + "字节)",
  22. })
  23. return
  24. }
  25. defer file.Close()
  26. fname := info.Filename
  27. fileSuffix := path.Ext(fname)
  28. re := regexp.MustCompile(*conAllowExt)
  29. if !re.MatchString(fileSuffix) {
  30. server.Log.Errorf("%s", "非法的文件格式"+fileSuffix)
  31. ctx.JSON(map[string]interface{}{
  32. "code": -2,
  33. "message": "非法的文件格式",
  34. })
  35. return
  36. }
  37. newname := fmt.Sprintf("%s%s", utils.UUID(), fileSuffix)
  38. newfile := fmt.Sprintf("%s/%s/%s", *conStaticPath, "tmp", newname)
  39. utils.CreateIfNotExist(newfile)
  40. out, err := os.OpenFile(newfile,
  41. os.O_WRONLY|os.O_CREATE, 0666)
  42. if err != nil {
  43. ctx.JSON(map[string]interface{}{
  44. "code": -3,
  45. "message": "文件上传失败:" + err.Error(),
  46. })
  47. return
  48. }
  49. defer out.Close()
  50. io.Copy(out, file)
  51. var fileURL string
  52. if *conDomain == "" {
  53. //fileURL = "http://" + server.GetHTTPHost() + "/upload/tmp/" + newname
  54. fileURL = fmt.Sprintf("http://%s/%s/%s/%s", server.GetHTTPHost(), *conStaticPath, "tmp", newname)
  55. } else {
  56. fileURL = fmt.Sprintf("%s/%s/%s/%s", *conDomain, *conStaticPath, "tmp", newname)
  57. }
  58. // save
  59. fc.addTempFile(newfile)
  60. ctx.JSON(map[string]interface{}{
  61. "code": 0,
  62. "message": "success",
  63. "file": fileURL,
  64. })
  65. return
  66. })
  67. }