savefilelogic.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. package logic
  2. import (
  3. "app.yhyue.com/moapp/jyfs/rpc/internal/config"
  4. "compress/gzip"
  5. "context"
  6. "errors"
  7. "fmt"
  8. "io/ioutil"
  9. "strings"
  10. "bytes"
  11. "app.yhyue.com/moapp/jyfs/rpc/filesystem"
  12. "app.yhyue.com/moapp/jyfs/rpc/internal/redis"
  13. "app.yhyue.com/moapp/jyfs/rpc/internal/svc"
  14. // "app.yhyue.com/moapp/jyfs/rpc/internal/redis"
  15. "github.com/aliyun/aliyun-oss-go-sdk/oss"
  16. "github.com/zeromicro/go-zero/core/logx"
  17. )
  18. type SaveFileLogic struct {
  19. ctx context.Context
  20. svcCtx *svc.ServiceContext
  21. logx.Logger
  22. }
  23. func NewSaveFileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SaveFileLogic {
  24. return &SaveFileLogic{
  25. ctx: ctx,
  26. svcCtx: svcCtx,
  27. Logger: logx.WithContext(ctx),
  28. }
  29. }
  30. // 保存文件
  31. func (l *SaveFileLogic) SaveFile(in *filesystem.SaveFileReq) (*filesystem.FileOpResp, error) {
  32. // 获取存储空间。
  33. bucket, err := l.svcCtx.OssClient.Bucket(in.Domain)
  34. if err != nil {
  35. return &filesystem.FileOpResp{State: false}, err
  36. }
  37. meta := redis.GetStr("jyfs", "jyfs_"+in.Domain)
  38. if meta != "" {
  39. for k, _ := range in.Meta {
  40. if !strings.Contains(meta, k) {
  41. return &filesystem.FileOpResp{}, errors.New("缺少元信息")
  42. }
  43. }
  44. }
  45. if len(in.RawFileContent) > 0 {
  46. content, _ := decompress(in.RawFileContent)
  47. if len(content) > 0 {
  48. in.RawFileContent = content
  49. }
  50. }
  51. // 设置文件元信息:过期时间为2049年1月10日 23:00:00 GMT,访问权限为公共读,自定义元信息为MyProp(取值MyPropVal)。
  52. // expires := time.Date(2049, time.January, 10, 23, 0, 0, 0, time.UTC)
  53. options := []oss.Option{
  54. // oss.Expires(expires),
  55. // oss.ObjectACL(oss.ACLPublicRead),
  56. // oss.Meta("MyProp", "MyPropVal"),
  57. }
  58. if in.Source == "docin" {
  59. if fs := strings.Split(in.FileId, "."); len(fs) > 1 {
  60. suffix := strings.ToLower(fs[1])
  61. if charset := config.Cf.ContentType[suffix]; charset != "" {
  62. options = append(options, oss.ContentType(fmt.Sprintf("text/plain; charset=%s", charset)))
  63. }
  64. }
  65. }
  66. for k, v := range in.Meta {
  67. options = append(options, oss.Meta(k, v))
  68. }
  69. // 上传Byte数组。
  70. err = bucket.PutObject(in.FileId, bytes.NewReader(in.RawFileContent), options...)
  71. if err != nil {
  72. return &filesystem.FileOpResp{}, err
  73. }
  74. return &filesystem.FileOpResp{State: true, FileId: in.FileId}, nil
  75. }
  76. func decompress(data []byte) ([]byte, error) {
  77. r, err := gzip.NewReader(bytes.NewBuffer(data))
  78. if err != nil {
  79. return nil, err
  80. }
  81. defer r.Close()
  82. return ioutil.ReadAll(r)
  83. }