package storage import ( "bytes" "context" "encoding/base64" "errors" "fmt" "mime/multipart" "stat/service/storage/proxy" "strconv" "sync" ) var ( buffer = bytes.Buffer{} mtx sync.Mutex ) // web后台上传使用, form-data方式上传 func UploadImage(ctx context.Context, f *multipart.FileHeader, domain string) (path string, err error) { if f == nil { return "", errors.New("file is nil!") } var file multipart.File if file, err = f.Open(); err != nil { return } defer file.Close() mtx.Lock() defer mtx.Unlock() buffer.Reset() if _, err = buffer.ReadFrom(file); err != nil { return } return proxy.UploadImg(f.Filename, buffer.Bytes(), domain) } func UploadVideoBody(ctx context.Context, form *multipart.Form, domain string) (*proxy.Result, error) { if form == nil { return nil, errors.New("multipart from is nil") } sb, err := makeShardBodyByForm(form) if err != nil { return nil, err } return proxy.UploadVideo(domain, sb) } func VideoBody(ctx context.Context, taskId, typ, domain string, pos int, data []byte) (*proxy.Result, error) { body := &proxy.ShardBody{ TaskId: taskId, Pos: pos, FileData: base64.StdEncoding.EncodeToString(data), Type: typ, } if typ == "1" { body.Type = "AV" } else if typ == "2" { body.Type = "SP" } return proxy.UploadVideo(domain, body) } func UploadVideoOK(ctx context.Context, in *proxy.BaseInfo, domain string) (*proxy.VideoOkResult, error) { if in.Type == "1" { in.Type = "AV" } else if in.Type == "2" { in.Type = "SP" } return proxy.PostOk(in, domain) } func makeShardBodyByForm(form *multipart.Form) (*proxy.ShardBody, error) { poss := form.Value["pos"] taskIds := form.Value["taskId"] types := form.Value["type"] fs := form.File["file"] totalPoss := form.Value["totalChunks"] var ( pos, total int taskId string typ string f *multipart.FileHeader err error ) if len(fs) == 0 || fs[0] == nil { return nil, errors.New("no file") } f = fs[0] if len(poss) == 0 || poss[0] == "" { return nil, errors.New("no pos") } if pos, err = strconv.Atoi(poss[0]); err != nil { return nil, fmt.Errorf("invalid pos") } if len(totalPoss) == 0 || totalPoss[0] == "" { return nil, errors.New("no totalPos") } if total, err = strconv.Atoi(totalPoss[0]); err != nil { return nil, fmt.Errorf("invalid totalPos") } if len(taskIds) == 0 || taskIds[0] == "" { return nil, errors.New("no pos") } taskId = taskIds[0] if len(types) == 0 || types[0] == "" { return nil, errors.New("no type") } if types[0] == "1" { typ = "AV" } else if types[0] == "2" { typ = "SP" } else { typ = types[0] } file, ne := f.Open() if ne != nil { return nil, ne } defer file.Close() mtx.Lock() defer mtx.Unlock() buffer.Reset() if _, err = buffer.ReadFrom(file); err != nil { return nil, err } resp := &proxy.ShardBody{ TaskId: taskId, Pos: pos, FileData: base64.StdEncoding.EncodeToString(buffer.Bytes()), Type: typ, TotalPos: total, } return resp, nil }