1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- package logic
- import (
- "app.yhyue.com/moapp/jyfs/rpc/internal/config"
- "compress/gzip"
- "context"
- "errors"
- "fmt"
- "io/ioutil"
- "strings"
- "bytes"
- "app.yhyue.com/moapp/jyfs/rpc/filesystem"
- "app.yhyue.com/moapp/jyfs/rpc/internal/redis"
- "app.yhyue.com/moapp/jyfs/rpc/internal/svc"
- // "app.yhyue.com/moapp/jyfs/rpc/internal/redis"
- "github.com/aliyun/aliyun-oss-go-sdk/oss"
- "github.com/zeromicro/go-zero/core/logx"
- )
- type SaveFileLogic struct {
- ctx context.Context
- svcCtx *svc.ServiceContext
- logx.Logger
- }
- func NewSaveFileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SaveFileLogic {
- return &SaveFileLogic{
- ctx: ctx,
- svcCtx: svcCtx,
- Logger: logx.WithContext(ctx),
- }
- }
- // 保存文件
- func (l *SaveFileLogic) SaveFile(in *filesystem.SaveFileReq) (*filesystem.FileOpResp, error) {
- // 获取存储空间。
- bucket, err := l.svcCtx.OssClient.Bucket(in.Domain)
- if err != nil {
- return &filesystem.FileOpResp{State: false}, err
- }
- meta := redis.GetStr("jyfs", "jyfs_"+in.Domain)
- if meta != "" {
- for k, _ := range in.Meta {
- if !strings.Contains(meta, k) {
- return &filesystem.FileOpResp{}, errors.New("缺少元信息")
- }
- }
- }
- if len(in.RawFileContent) > 0 {
- in.RawFileContent, _ = decompress(in.RawFileContent)
- }
- // 设置文件元信息:过期时间为2049年1月10日 23:00:00 GMT,访问权限为公共读,自定义元信息为MyProp(取值MyPropVal)。
- // expires := time.Date(2049, time.January, 10, 23, 0, 0, 0, time.UTC)
- options := []oss.Option{
- // oss.Expires(expires),
- // oss.ObjectACL(oss.ACLPublicRead),
- // oss.Meta("MyProp", "MyPropVal"),
- }
- if fs := strings.Split(in.FileId, "."); len(fs) > 1 {
- suffix := fs[1]
- if charset := config.Cf.ContentType[suffix]; charset != "" {
- options = append(options, oss.ContentType(fmt.Sprintf("text/plain; charset=%s", charset)))
- }
- }
- for k, v := range in.Meta {
- options = append(options, oss.Meta(k, v))
- }
- // 上传Byte数组。
- err = bucket.PutObject(in.FileId, bytes.NewReader(in.RawFileContent), options...)
- if err != nil {
- return &filesystem.FileOpResp{}, err
- }
- return &filesystem.FileOpResp{State: true, FileId: in.FileId}, nil
- }
- func decompress(data []byte) ([]byte, error) {
- r, err := gzip.NewReader(bytes.NewBuffer(data))
- if err != nil {
- return nil, err
- }
- defer r.Close()
- return ioutil.ReadAll(r)
- }
|