Skip to content
This repository was archived by the owner on Apr 1, 2022. It is now read-only.

UploadObject上传一个文件,为什么content-length一直为0 #8

Closed
kapujiang opened this issue Apr 8, 2018 · 2 comments
Closed

Comments

@kapujiang
Copy link

kapujiang commented Apr 8, 2018

`
func UploadObject() {
bu := "kapucostest"
ctx := cos.GetTimeoutCtx(time.Second * 30)
objName := "img.jpg"
f,err := os.Open("img.jpg")
if err != nil {
fmt.Println(err.Error())
return
}
defer f.Close()

err = client.Bucket(bu).UploadObject(ctx, objName, f, &cos.AccessControl{})

if err != nil {
    fmt.Println(err.Error())
} 

}
`

输出:
Put Object:
411:请求被拒绝You must provide the Content-Length HTTP header.

@kapujiang kapujiang changed the title uploadFile 上传一个文件,为什么content-length一直为0 UploadObject上传一个文件,为什么content-length一直为0 Apr 8, 2018
@kapujiang
Copy link
Author

这样处理能够拿到contentlength
rc, ok := body.(io.ReadCloser)
if !ok && body != nil {
rc = ioutil.NopCloser(body)
}
req.Body = rc
switch v := body.(type) {
case *bytes.Buffer:
req.ContentLength = int64(v.Len())
case *bytes.Reader:
req.ContentLength = int64(v.Len())
case *strings.Reader:
req.ContentLength = int64(v.Len())
case *os.File:
req.ContentLength = tryGetFileSize(v)
}

@nelsonken
Copy link
Owner

解决了:参考 https://golang.org/pkg/net/http/#NewRequest

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants