功能说明
上传一个对象(文件/对象)至高性能桶(PUT Object)。对高性能桶发起上传请求时,SDK 通过
RapidCredentialTransport 自动完成会话鉴权。方法原型
func (s *ObjectService) Put(ctx context.Context, name string, r io.Reader, opt *ObjectPutOptions) (*Response, error)func (s *ObjectService) PutFromFile(ctx context.Context, name string, filePath string, opt *ObjectPutOptions) (*Response, error)
参数说明
type ObjectPutOptions struct {*ObjectPutHeaderOptions}type ObjectPutHeaderOptions struct {CacheControl stringContentDisposition stringContentEncoding stringContentType stringContentMD5 stringContentLength int64ContentLanguage stringExpires string// 自定义的 x-cos-meta-* headerXCosMetaXXX *http.HeaderXCosStorageClass string}
参数名称 | 参数描述 | 类型 | 是否必选 |
ctx | 请求上下文,用于控制超时与取消 | context.Context | 是 |
name | 对象键(Object Key),即对象在桶中的完整路径 | string | 是 |
r | 上传对象的内容,可为文件流或字节流;当 r 不是 bytes.Buffer/bytes.Reader/strings.Reader 时,必须指定 opt.ObjectPutHeaderOptions.ContentLength | io.Reader | 是 |
opt | 上传选项,可为 nil | *ObjectPutOptions | 否 |
ContentType | 内容类型,设置 Content-Type | string | 否 |
ContentLength | 设置传输长度 | int64 | 否 |
ContentMD5 | 请求体内容的 MD5 校验值(Base64 编码),用于完整性校验 | string | 否 |
CacheControl | 缓存策略,设置 Cache-Control | string | 否 |
ContentDisposition | 文件名展示方式,设置 Content-Disposition | string | 否 |
ContentEncoding | 编码格式,设置 Content-Encoding | string | 否 |
ContentLanguage | 内容语言,设置 Content-Language | string | 否 |
Expires | 设置 Expires | string | 否 |
XCosMetaXXX | 用户自定义的对象元信息,必须以 x-cos-meta- 开头,否则会被忽略 | *http.Header | 否 |
XCosStorageClass | 存储类型,高性能桶仅支持默认值( RAPID) | string | 否 |
返回结果说明
返回的响应头可通过
Response.Header 获取,例如 ETag:resp, err := c.Object.Put(context.Background(), name, f, nil)etag := resp.Header.Get("ETag")
参数名称 | 参数描述 | 类型 |
*Response | 响应对象,可从中读取响应头(如 ETag) | *cos.Response |
ETag | 上传对象的 MD5 值,从响应头读取 | string |
error | 错误信息,成功时为 nil | error |
使用案例
package mainimport ("context""log""net/http""net/url""os""strings""time""github.com/tencentyun/cos-go-sdk-v5")func main() {u, _ := url.Parse("https://examplebucket-x--1250000000.cosrapid.ap-guangzhou.myqcloud.com")b := &cos.BaseURL{BucketURL: u}base := &cos.AuthorizationTransport{SecretID: os.Getenv("SECRETID"),SecretKey: os.Getenv("SECRETKEY"),}c := cos.NewClient(b, &http.Client{Transport: cos.NewRapidCredentialTransport(base),Timeout: 30 * time.Second,})ctx := context.Background()name := "exampleobject.txt"content := strings.NewReader("hello rapid bucket")opt := &cos.ObjectPutOptions{ObjectPutHeaderOptions: &cos.ObjectPutHeaderOptions{ContentType: "text/plain",},}_, err := c.Object.Put(ctx, name, content, opt)if err != nil {log.Fatalf("PutObject failed: %v", err)}log.Println("PutObject OK")}
注意事项
上传本地文件时,可直接使用
PutFromFile,或用 os.Open 打开文件并将 *os.File 作为 io.Reader 传入 Put。大文件建议使用分块上传,详见 初始化分块上传。
对象键不应以
/ 开头,也不应为空。