savefilelogic.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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 fs := strings.Split(in.FileId, "."); len(fs) > 1 && in.Charset != "" {
  59. if suffix := strings.ToLower(fs[1]); suffix == "txt" {
  60. for _, v := range strings.Split(config.Cf.ContentType, ",") {
  61. if v == suffix {
  62. options = append(options, oss.ContentType(fmt.Sprintf("text/plain; charset=%s", in.Charset)))
  63. break
  64. }
  65. }
  66. }
  67. }
  68. for k, v := range in.Meta {
  69. options = append(options, oss.Meta(k, v))
  70. }
  71. // 上传Byte数组。
  72. err = bucket.PutObject(in.FileId, bytes.NewReader(in.RawFileContent), options...)
  73. if err != nil {
  74. return &filesystem.FileOpResp{}, err
  75. }
  76. return &filesystem.FileOpResp{State: true, FileId: in.FileId}, nil
  77. }
  78. func decompress(data []byte) ([]byte, error) {
  79. r, err := gzip.NewReader(bytes.NewBuffer(data))
  80. if err != nil {
  81. return nil, err
  82. }
  83. defer r.Close()
  84. return ioutil.ReadAll(r)
  85. }