fileuploadlogic.go 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package logic
  2. import (
  3. "context"
  4. "fmt"
  5. "io/ioutil"
  6. "net/http"
  7. "strings"
  8. "app.yhyue.com/moapp/jybase/common"
  9. fpb "bp.jydev.jianyu360.cn/BaseService/fileCenter/rpc/pb"
  10. cm "bp.jydev.jianyu360.cn/CRM/application/api/common"
  11. "bp.jydev.jianyu360.cn/CRM/application/api/internal/svc"
  12. "bp.jydev.jianyu360.cn/CRM/application/api/internal/types"
  13. "bp.jydev.jianyu360.cn/CRM/application/service"
  14. "github.com/zeromicro/go-zero/core/logx"
  15. )
  16. type FileUploadLogic struct {
  17. logx.Logger
  18. ctx context.Context
  19. svcCtx *svc.ServiceContext
  20. r *http.Request
  21. }
  22. func NewFileUploadLogic(ctx context.Context, svcCtx *svc.ServiceContext, r *http.Request) *FileUploadLogic {
  23. return &FileUploadLogic{
  24. Logger: logx.WithContext(ctx),
  25. ctx: ctx,
  26. svcCtx: svcCtx,
  27. r: r,
  28. }
  29. }
  30. func (l *FileUploadLogic) FileUpload(req *types.FileUploadReq) (resp *types.Reply, err error) {
  31. resp = &types.Reply{}
  32. file, header, _ := l.r.FormFile("file")
  33. status := 1
  34. defer file.Close()
  35. bt, _ := ioutil.ReadAll(file)
  36. up, err := cm.FileCenterRpc.Upload(l.ctx, &fpb.UploadReq{
  37. File: bt,
  38. OssBucketName: cm.C.OssBucketName,
  39. OssUrl: cm.C.OssUrl,
  40. Name: header.Filename,
  41. })
  42. if up == nil || up.Url == "" {
  43. resp.Error_code = -1
  44. resp.Error_msg = "上传失败"
  45. resp.Data = map[string]interface{}{"status": -1}
  46. return
  47. }
  48. key := up.Key
  49. size := fmt.Sprintf("%.4f", common.Float64All(header.Size)/1024)
  50. for {
  51. if strings.HasSuffix(size, "0") {
  52. size = strings.TrimRight(size, "0")
  53. continue
  54. }
  55. if strings.HasSuffix(size, ".") {
  56. size = strings.TrimRight(size, ".")
  57. break
  58. }
  59. break
  60. }
  61. fileSize := size + "KB"
  62. var data map[string]interface{}
  63. fileTypeTmp := strings.Split(header.Filename, ".")
  64. var ftype string
  65. if len(fileTypeTmp) > 0 && len(fileTypeTmp) == 2 {
  66. ftype = strings.Split(header.Filename, ".")[1]
  67. }
  68. fl := &service.File{
  69. Name: header.Filename, //附件名称
  70. Suffix: ftype, //文件后缀
  71. FileType: req.FileType, //文件类型,产品介绍、项目方案、立项报告、报价文件、招标文件、投标文件、中标通知书、合同、发票、其他文件
  72. Size: fileSize, //文件大小
  73. Oss: up.Url, //oss地址
  74. BusinessId: req.BusinessId, //业务id
  75. Types: req.Types, //类型;1:跟进记录-线下 2:跟进记录-线上 3:跟进记录-备忘 4:销售机会-项目文档 5:客户-客户档案
  76. }
  77. if !fl.Add() {
  78. status = -1
  79. }
  80. data = map[string]interface{}{
  81. "filename": header.Filename,
  82. "ftype": ftype,
  83. "fid": key,
  84. "size": fileSize,
  85. "ossurl": cm.C.OssUrl,
  86. "url": up.Url,
  87. "status": status,
  88. }
  89. resp.Data = data
  90. return
  91. }