savefilelogic.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. in.RawFileContent, _ = decompress(in.RawFileContent)
  47. }
  48. // 设置文件元信息:过期时间为2049年1月10日 23:00:00 GMT,访问权限为公共读,自定义元信息为MyProp(取值MyPropVal)。
  49. // expires := time.Date(2049, time.January, 10, 23, 0, 0, 0, time.UTC)
  50. options := []oss.Option{
  51. // oss.Expires(expires),
  52. // oss.ObjectACL(oss.ACLPublicRead),
  53. // oss.Meta("MyProp", "MyPropVal"),
  54. }
  55. if fs := strings.Split(in.FileId, "."); len(fs) > 1 {
  56. suffix := fs[1]
  57. if charset := config.Cf.ContentType[suffix]; charset != "" {
  58. options = append(options, oss.ContentType(fmt.Sprintf("text/plain; charset=%s", charset)))
  59. }
  60. }
  61. for k, v := range in.Meta {
  62. options = append(options, oss.Meta(k, v))
  63. }
  64. // 上传Byte数组。
  65. err = bucket.PutObject(in.FileId, bytes.NewReader(in.RawFileContent), options...)
  66. if err != nil {
  67. return &filesystem.FileOpResp{}, err
  68. }
  69. return &filesystem.FileOpResp{State: true, FileId: in.FileId}, nil
  70. }
  71. func decompress(data []byte) ([]byte, error) {
  72. r, err := gzip.NewReader(bytes.NewBuffer(data))
  73. if err != nil {
  74. return nil, err
  75. }
  76. defer r.Close()
  77. return ioutil.ReadAll(r)
  78. }