upload.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. return
  39. }
  40. // 设置 HTTP 响应头
  41. this.SetHeader("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, extractNameFromPath(file_path)))
  42. this.SetHeader("Content-Type", "application/octet-stream")
  43. this.SetHeader("Content-Length", fmt.Sprintf("%d", len(fileBytes)))
  44. this.WriteBytes(fileBytes)
  45. return
  46. }
  47. this.Write("未找到附件")
  48. }
  49. //
  50. func extractNameFromPath(path string) string {
  51. // 使用 strings.LastIndex 寻找最后一个斜杠的索引
  52. index := strings.LastIndex(path, "/")
  53. if index == -1 {
  54. // 如果没有斜杠,则返回整个路径
  55. return path
  56. }
  57. // 提取最后一个斜杠后面的名称
  58. if index+1 < len(path) {
  59. name := path[index+1:]
  60. return name
  61. }
  62. // 如果索引超出范围,则返回空字符串
  63. return ""
  64. }