node_static.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package core
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "image"
  6. "io/ioutil"
  7. "net/http"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "sync"
  12. "github.com/gin-gonic/gin"
  13. )
  14. var statics sync.Map
  15. func addStatic(uuid, path string) {
  16. statics.Store(uuid, path)
  17. }
  18. func remStatic(uuid string) {
  19. statics.Delete(uuid)
  20. }
  21. func FindFile(c *gin.Context) {
  22. // 获取文件名
  23. filename := c.Param("filename")
  24. statics.Range(func(_, value any) bool {
  25. path := value.(string)
  26. // 拼接文件路径
  27. filepath := strings.ReplaceAll(filepath.Join(path, filename), "\\/", "\\")
  28. // 判断文件是否存在
  29. _, err := os.Stat(filepath)
  30. if err == nil {
  31. // 文件存在,读取文件内容并返回
  32. file, err := ioutil.ReadFile(filepath)
  33. if err != nil {
  34. c.AbortWithError(http.StatusInternalServerError, err)
  35. return true
  36. }
  37. // 根据文件类型设置Content-Type
  38. contentType := http.DetectContentType(file)
  39. c.Header("Content-Type", contentType)
  40. // 返回文件内容
  41. c.Data(http.StatusOK, contentType, file)
  42. return false
  43. } else {
  44. console.Log(err)
  45. }
  46. return true
  47. })
  48. // 如果文件不存在,返回404错误
  49. c.AbortWithStatus(http.StatusNotFound)
  50. }
  51. // Server.GET("/api/file/:filename", FindFile)
  52. // Server.GET("/api/decode/:random", Base642Binary)
  53. func Base642Binary(c *gin.Context) {
  54. random := c.Param("random")
  55. s, ok := temp.Get("base64_" + random).(string)
  56. if !ok {
  57. c.String(http.StatusBadRequest, "Invalid input")
  58. return
  59. }
  60. input := strings.TrimPrefix(s, "base64://")
  61. data, err := base64.StdEncoding.DecodeString(input)
  62. if err != nil {
  63. c.String(http.StatusBadRequest, "Invalid input")
  64. return
  65. }
  66. // 解析图片格式
  67. _, format, err := image.DecodeConfig(strings.NewReader(string(data)))
  68. fmt.Println(format, err)
  69. if err != nil {
  70. c.Header("Content-Type", "application/octet-stream")
  71. } else {
  72. // 根据图片格式设置响应头
  73. switch format {
  74. case "jpeg":
  75. c.Header("Content-Type", "image/jpeg")
  76. case "png":
  77. c.Header("Content-Type", "image/png")
  78. default:
  79. c.Header("Content-Type", "application/octet-stream")
  80. return
  81. }
  82. }
  83. c.Data(http.StatusOK, "application/octet-stream", data)
  84. }