savefilelogic.go 2.0 KB

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