upload.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package action
  2. import (
  3. "fmt"
  4. "log"
  5. "strings"
  6. "yunpanWeb/service/config"
  7. "app.yhyue.com/moapp/jybase/go-xweb/xweb"
  8. "github.com/gogf/gf/v2/util/gconv"
  9. // "github.com/studio-b12/gowebdav"
  10. "app.yhyue.com/moapp/jybase/encrypt"
  11. )
  12. type UploadAction struct {
  13. *xweb.Action
  14. upload xweb.Mapper `xweb:"/upload/(\\w+)/(.*)"`
  15. }
  16. func init() {
  17. xweb.AddAction(&UploadAction{})
  18. }
  19. func (this *UploadAction) Upload(stype, sid string) {
  20. log.Println(stype, sid)
  21. id := encrypt.DecodeArticleId2ByCheck(sid)[0]
  22. table := config.Sysconfig.UrlMap[stype]
  23. if id == "" || table == "" {
  24. this.Write("未找到附件")
  25. return
  26. }
  27. data := &map[string]interface{}{}
  28. for _, v := range config.Sysconfig.TableMap[table] {
  29. if data != nil && len(*data) > 0 {
  30. continue
  31. }
  32. data, _ = config.MQFW.FindById(v, id, `{"file_path":1}`)
  33. }
  34. if data != nil && len(*data) > 0 {
  35. file_path := gconv.String((*data)["file_path"])
  36. fileBytes, err := config.Client.Read(file_path)
  37. if err != nil {
  38. log.Println("Read err:", err)
  39. return
  40. }
  41. // log.Println("fileBytes:", len(fileBytes))
  42. // 设置 HTTP 响应头
  43. this.SetHeader("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, extractNameFromPath(file_path)))
  44. this.SetHeader("Content-Type", "application/octet-stream")
  45. // this.SetHeader("Content-Length", fmt.Sprintf("%d", len(fileBytes)))
  46. err = this.WriteBytes(fileBytes)
  47. if err != nil {
  48. log.Println("write err:", err)
  49. }
  50. return
  51. }
  52. this.Write("未找到附件")
  53. }
  54. //
  55. func extractNameFromPath(path string) string {
  56. // 使用 strings.LastIndex 寻找最后一个斜杠的索引
  57. index := strings.LastIndex(path, "/")
  58. if index == -1 {
  59. // 如果没有斜杠,则返回整个路径
  60. return path
  61. }
  62. // 提取最后一个斜杠后面的名称
  63. if index+1 < len(path) {
  64. name := path[index+1:]
  65. return name
  66. }
  67. // 如果索引超出范围,则返回空字符串
  68. return ""
  69. }