API | Operation | Description |
Uploading an object using simple upload | Uploads an object to a bucket | |
Appending parts | Uploads an object by appending parts |
API | Operation | Description |
Querying multipart uploads | Queries in-progress multipart uploads. | |
Initializing a multipart upload operation | Initializes a multipart upload operation. | |
Uploading parts | Uploads a file in parts. | |
Querying uploaded parts | Queries the uploaded parts of a multipart upload. | |
Completing a multipart upload | Completes the multipart upload of a file. | |
Aborting a multipart upload | Aborts a multipart upload and deletes the uploaded parts. |
PartSize
parameter to adjust the part size.func (s *ObjectService) Upload(ctx context.Context, key string, filepath string, opt *MultiUploadOptions) (*CompleteMultipartUploadResult, *Response, error)
package mainimport ("context""github.com/tencentyun/cos-go-sdk-v5""net/http""net/url""os")func main(){// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.// Replace it with your region, which can be viewed in the COS console at https://console.tencentcloud.com/. For more information about regions, visit https://www.tencentcloud.com/document/product/436/6224.u, _ := url.Parse("https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com")b := &cos.BaseURL{BucketURL: u}client := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{// Get the key from environment variables// Environment variable `SECRETID` refers to the user's `SecretId`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.// Environment variable `SECRETKEY` refers to the user's `SecretKey`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretKey: os.Getenv("SECRETKEY"), // User `SecretKey`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.},})key := "exampleobject"_, _, err := client.Object.Upload(context.Background(), key, "localfile", nil,)if err != nil{panic(err)}}
type MultiUploadOptions struct {OptIni *InitiateMultipartUploadOptionsPartSize int64ThreadPoolSize intCheckPoint bool}
Parameter | Description | Type | Required |
key | Object key, unique identifier of an object in a bucket. For example, if the object endpoint is examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/pic.jpg , its object key is doc/pic.jpg | String | Yes |
filepath | Name of the local file | String | Yes |
opt | Object attributes | Struct | No |
OptIni | Sets object attributes and ACL. For details, see InitiateMultipartUploadOptions | Struct | No |
PartSize | Part size (in MB). If this parameter is not specified or is set to a value smaller than or equal to 0, its value will be automatically determined. In the new version, the default size is 16 (MB). | Int | No |
ThreadPoolSize | Size of the thread pool. Default value: 1 | Int | No |
CheckPoint | Whether to enable checkpoint restart. Default value: false | Bool | No |
type CompleteMultipartUploadResult struct {Location stringBucket stringKey stringETag string}
Parameter | Description | Type |
Location | URL | String |
Bucket | Bucket name in the format of BucketName-APPID , for example, examplebucket-1250000000 | String |
Key | Object key, the unique identifier of an object in a bucket. For example, if the object endpoint is examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/pic.jpg , its object key is doc/pic.jpg | string |
ETag | Unique tag of a merged object. This value does not represent the MD5 checksum of the object content, but is used only to verify the uniqueness of the object as a whole. To verify the object content, you can check the ETag of each part during the upload process | String |
func (s *ObjectService) Put(ctx context.Context, key string, r io.Reader, opt *ObjectPutOptions) (*Response, error)func (s *ObjectService) PutFromFile(ctx context.Context, name string, filePath string, opt *ObjectPutOptions) (*Response, error)
package mainimport ("context""github.com/tencentyun/cos-go-sdk-v5""net/http""net/url""os""strings")func main(){// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.// Replace it with your region, which can be viewed in the COS console at https://console.tencentcloud.com/. For more information about regions, visit https://www.tencentcloud.com/document/product/436/6224.u, _ := url.Parse("https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com")b := &cos.BaseURL{BucketURL: u}client := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{// Get the key from environment variables// Environment variable `SECRETID` refers to the user's `SecretId`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.// Environment variable `SECRETKEY` refers to the user's `SecretKey`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretKey: os.Getenv("SECRETKEY"), // User `SecretKey`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.},})// Sample 1: Using Put to upload an objectkey := "exampleobject"f, err := os.Open("../test")opt := &cos.ObjectPutOptions{ObjectPutHeaderOptions: &cos.ObjectPutHeaderOptions{ContentType: "text/html",},ACLHeaderOptions: &cos.ACLHeaderOptions{// Considering the ACL limit, we recommend you not set an object ACL when uploading an object unless required. The object will then inherit the bucket ACL by default.XCosACL: "private",},}_, err = client.Object.Put(context.Background(), key, f, opt)if err != nil{panic(err)}// Sample 2: Using PUtFromFile to upload a file to COSfilepath := "./test"_, err = client.Object.PutFromFile(context.Background(), key, filepath, opt)if err != nil{panic(err)}// Sample 3: Uploading a zero-byte file and setting the input stream length to 0_, err = client.Object.Put(context.Background(), key, strings.NewReader(""), nil)if err != nil{// ERROR}}
package mainimport ("context""github.com/tencentyun/cos-go-sdk-v5""net/http""net/url""os""strings")func main(){// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.// Replace it with your region, which can be viewed in the COS console at https://console.tencentcloud.com/. For more information about regions, visit https://www.tencentcloud.com/document/product/436/6224.u, _ := url.Parse("https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com")b := &cos.BaseURL{BucketURL: u}client := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{// Get the key from environment variables// Environment variable `SECRETID` refers to the user's `SecretId`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.// Environment variable `SECRETKEY` refers to the user's `SecretKey`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretKey: os.Getenv("SECRETKEY"), // User `SecretKey`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.},})// Folder namename := "folder/"// Transfer an input stream whose size is 0._, err := client.Object.Put(context.Background(), name, strings.NewReader(""), nil)if err != nil{// ERROR}}
dir
.package mainimport ("context""github.com/tencentyun/cos-go-sdk-v5""net/http""net/url""os""strings")func main(){// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.// Replace it with your region, which can be viewed in the COS console at https://console.tencentcloud.com/. For more information about regions, visit https://www.tencentcloud.com/document/product/436/6224.u, _ := url.Parse("https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com")b := &cos.BaseURL{BucketURL: u}client := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{// Get the key from environment variables// Environment variable `SECRETID` refers to the user's `SecretId`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.// Environment variable `SECRETKEY` refers to the user's `SecretKey`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretKey: os.Getenv("SECRETKEY"), // User `SecretKey`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.},})dir := "exampledir/"filename := "exampleobject"key := dir + filenamef := strings.NewReader("test file")_, err = client.Object.Put(context.Background(), key, f, nil)if err != nil{// ERROR}}
package mainimport ("context""fmt""github.com/tencentyun/cos-go-sdk-v5""net/http""net/url""os")type SelfListener struct {}// A custom progress callback, which requires the ProgressChangedCallback method to be implemented.func (l *SelfListener) ProgressChangedCallback(event *cos.ProgressEvent) {switch event.EventType {case cos.ProgressDataEvent:fmt.Printf("\\r[ConsumedBytes/TotalBytes: %d/%d, %d%%]",event.ConsumedBytes, event.TotalBytes, event.ConsumedBytes*100/event.TotalBytes)case cos.ProgressFailedEvent:fmt.Printf("\\nTransfer Failed: %v", event.Err)}}func main(){// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.// Replace it with your region, which can be viewed in the COS console at https://console.tencentcloud.com/. For more information about regions, visit https://www.tencentcloud.com/document/product/436/6224.u, _ := url.Parse("https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com")b := &cos.BaseURL{BucketURL: u}client := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{// Get the key from environment variables// Environment variable `SECRETID` refers to the user's `SecretId`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.// Environment variable `SECRETKEY` refers to the user's `SecretKey`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretKey: os.Getenv("SECRETKEY"), // User `SecretKey`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.},})// Sample 1: Using the default callback function to view the upload progresskey := "exampleobject"f, err := os.Open("test")opt := &cos.ObjectPutOptions{ObjectPutHeaderOptions: &cos.ObjectPutHeaderOptions{ContentType: "text/html",// Set the default progress callback function.Listener: &cos.DefaultProgressListener{},},ACLHeaderOptions: &cos.ACLHeaderOptions{// Considering the ACL limit, we recommend you not set an object ACL when uploading an object unless required. The object will then inherit the bucket ACL by default.XCosACL: "private",},}_, err = client.Object.Put(context.Background(), key, f, opt)if err != nil{panic(err)}// Sample 2: Using a custom way to view the upload progressopt.Listener = &SelfListener{}filepath := "./test"_, err = client.Object.PutFromFile(context.Background(), key, filepath, opt)if err != nil{panic(err)}}
package mainimport ("context""github.com/tencentyun/cos-go-sdk-v5""net/http""net/url""os""sync")func upload(wg *sync.WaitGroup, c *cos.Client, files <-chan string) {defer wg.Done()for file := range files {name := "folder/" + filefd, err := os.Open(file)if err != nil{//ERRORcontinue}_, err = c.Object.Put(context.Background(), name, fd, nil)if err != nil{//ERROR}}}func main(){u, _ := url.Parse("https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com")b := &cos.BaseURL{BucketURL: u}c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.SecretKey: os.Getenv("SECRETKEY"), // User `SecretKey`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.},})// Upload files with multiple threadsfilesCh := make(chan string, 2)filePaths := []string{"test1", "test2", "test3"}var wg sync.WaitGroupthreadpool := 2for i := 0; i < threadpool; i++ {wg.Add(1)go upload(&wg, c, filesCh)}for _, filePath := range filePaths {filesCh <- filePath}close(filesCh)wg.Wait()}
package mainimport ("context""crypto/md5""encoding/base64""fmt""github.com/tencentyun/cos-go-sdk-v5""io/ioutil""net/http""net/url""os""strings")func calMD5Digest(msg []byte) []byte {m := md5.New()m.Write(msg)return m.Sum(nil)}func main(){u, _ := url.Parse("https://test-1259654469.cos.ap-guangzhou.myqcloud.com")b := &cos.BaseURL{BucketURL: u}c := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{// Environment variable `SECRETID` refers to the user's `SecretId`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.// Environment variable `SECRETKEY` refers to the user's `SecretKey`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretKey: os.Getenv("SECRETKEY"), // User `SecretKey`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.},})// CRC64 check is enabled by default in the Go SDK v0.7.23 or later.// c.Conf.EnableCRC = false // Manually disable CRC64 check, which is not recommended.// Calculate MD5.content := "test content"bs1 := calMD5Digest([]byte(content))md5str := fmt.Sprintf("%x", bs1)name := "exampleobject"f := strings.NewReader(content)opt := &cos.ObjectPutOptions{ObjectPutHeaderOptions: &cos.ObjectPutHeaderOptions{ContentMD5: base64.StdEncoding.EncodeToString(bs1), // The server can perform a check based on the received file and this value during uploadXCosMetaXXX: &http.Header{},},ACLHeaderOptions: nil,}opt.XCosMetaXXX.Add("x-cos-meta-md5", md5str) // The business can use this value for file check during download// Upload the file_, err := c.Object.Put(context.Background(), name, f, opt)if err != nil{// ERROR}// Download a file.resp, err := c.Object.Get(context.Background(), name, nil)if err != nil{// ERROR}defer resp.Body.Close()meta_md5 := resp.Header.Get("x-cos-meta-md5")body, _ := ioutil.ReadAll(resp.Body)bs2 := calMD5Digest(body)if fmt.Sprintf("%x", bs2) != meta_md5 {fmt.Printf("md5 is not consistent\\n")}}
type ObjectPutOptions struct {*ACLHeaderOptions*ObjectPutHeaderOptions}type ACLHeaderOptions struct {XCosACL stringXCosGrantRead stringXCosGrantWrite stringXCosGrantFullControl string}type ObjectPutHeaderOptions struct {CacheControl stringContentDisposition stringContentEncoding stringContentType stringContentMD5 stringContentLength int64Expires string// Custom x-cos-meta-* headerXCosMetaXXX *http.HeaderXCosStorageClass stringXCosTrafficLimit intListener ProgressListener}
Parameter | Description | Type | Required |
r | Content of the uploaded file, which can be a file stream or a byte stream. When r is not bytes.Buffer/bytes.Reader/strings.Reader , opt.ObjectPutHeaderOptions.ContentLength must be specified | io.Reader | Yes |
key | ObjectKey is the unique identifier of an object in a bucket. For example, in the object's access domain name examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/pic.jpg , the ObjectKey is doc/pic.jpg . | String | Yes |
XCosACL | Sets the file ACL, such as private, public-read, and public-read-write | String | No |
XCosGrantFullControl | Grants full permission in the format: id="[OwnerUin]" | String | No |
XCosGrantRead | Grants read permission in the format: id="[OwnerUin]" | String | No |
XCosStorageClass | Storage class of the object, such as STANDARD (default), STANDARD_IA , and ARCHIVE . For more information, see Storage Class Overview. | string | No |
Expires | Sets Content-Expires | String | No |
CacheControl | Cache policy. Sets Cache-Control | String | No |
ContentType | Content Type. Sets Content-Type | String | No |
ContentMD5 | Base64-encoded MD5 checksum of the request body content defined in RFC 1864. This value is a 24-character string, such as ZzD3iDJdrMAAb00lgLLeig== , and is used to verify whether the request body experienced any changes during transfer. | string | No |
ContentDisposition | Filename. Sets Content-Disposition | String | No |
ContentEncoding | Encoding format. Sets Content-Encoding | String | No |
ContentLength | Sets the length of the request content | Int64 | No |
XCosMetaXXX | User-defined file metadata. It must start with x-cos-meta. Otherwise, it will be ignored | http.Header | No |
XCosTrafficLimit | Speed limit for a single URL | Int | No |
Listener | Progress callback API | Struct | No |
{'ETag': 'string','x-cos-expiration': 'string'}
response
.resp, err := client.Object.Put(context.Background(), key, f, nil)etag := resp.Header.Get("ETag")exp := resp.Header.Get("x-cos-expiration")
Parameter | Description | Type |
ETag | MD5 checksum of the uploaded file | string |
x-cos-expiration | Returns the file expiration rule if a lifecycle is configured. | string |
func (s *ObjectService) Append(ctx context.Context, name string, position int, r io.Reader, opt *ObjectPutOptions) (int, *Response, error)
package mainimport ("context""github.com/tencentyun/cos-go-sdk-v5""net/http""net/url""os""strings")func main(){// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.// Replace it with your region, which can be viewed in the COS console at https://console.tencentcloud.com/. For more information about regions, visit https://www.tencentcloud.com/document/product/436/6224.u, _ := url.Parse("https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com")b := &cos.BaseURL{BucketURL: u}client := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{// Get the key from environment variables// Environment variable `SECRETID` refers to the user's `SecretId`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.// Environment variable `SECRETKEY` refers to the user's `SecretKey`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretKey: os.Getenv("SECRETKEY"), // User `SecretKey`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.},})name := "exampleobject"pos, _, err := client.Object.Append(context.Background(), name, 0, strings.NewReader("test1"), nil)if err != nil{// ERROR}_, _, err = client.Object.Append(context.Background(), name, pos, strings.NewReader("test2"), nil)if err != nil{// ERROR}}
Parameter | Description | Type |
name | Object key, unique identifier of an object in a bucket. For example, if the object endpoint is examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/pic.jpg , its object key is doc/pic.jpg . | String |
position | Starting point for the append operation (in bytes). For the first append, the value of this parameter is 0. For subsequent appends, the value is the content-length of the current object. | int |
r | Content of the uploaded file, which can be a file stream or a byte stream. When r is not bytes.Buffer/bytes.Reader/strings.Reader , opt.ObjectPutHeaderOptions.ContentLength must be specified | io.Reader |
opt | Uploaded parameter. For more information, see ObjectPutOptions | struct |
Parameter | Description | Type |
x-cos-next-append-position | Starting point of the next append, in bytes | int |
func (s *BucketService) ListMultipartUploads(ctx context.Context, opt *ListMultipartUploadsOptions) (*ListMultipartUploadsResult, *Response, error)
package mainimport ("context""github.com/tencentyun/cos-go-sdk-v5""net/http""net/url""os")func main(){// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.// Replace it with your region, which can be viewed in the COS console at https://console.tencentcloud.com/. For more information about regions, visit https://www.tencentcloud.com/document/product/436/6224.u, _ := url.Parse("https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com")b := &cos.BaseURL{BucketURL: u}client := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{// Get the key from environment variables// Environment variable `SECRETID` refers to the user's `SecretId`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.// Environment variable `SECRETKEY` refers to the user's `SecretKey`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretKey: os.Getenv("SECRETKEY"), // User `SecretKey`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.},})_, _, err := client.Bucket.ListMultipartUploads(context.Background(), nil)if err != nil{panic(err)}}
type ListMultipartUploadsOptions struct {Delimiter stringEncodingType stringPrefix stringMaxUploads intKeyMarker stringUploadIDMarker string}
Parameter | Description | Type | Required |
delimiter | The delimiter is a symbol. The identical paths between prefix or, if no prefix is specified, the beginning and the first delimiter are grouped and defined as a common prefix | String | No |
encodingType | Encoding type of the returned value. Valid value: url | String | No |
prefix | Specifies that returned object keys must be prefixed with this value. Note that if you use this parameter, returned keys will contain the prefix | String | No |
MaxUploads | Sets the maximum number of multipart uploads that can be returned at a time. Value range: 1−1000. Defaults to 1000 . | Int | No |
KeyMarker | This parameter is used together with upload-id-marker : If upload-id-marker is not specified, multipart uploads whose ObjectName is lexicographically greater than key-marker will be listed.If upload-id-marker is specified, multipart uploads whose ObjectName is lexicographically greater than key-marker will be listed, and multipart uploads whose ObjectName is lexicographically equal to key-marker with UploadID greater than upload-id-marker will be listed. | String | No |
UploadIDMarker | This parameter is used together with key-marker : If key-marker is not specified, upload-id-marker will be ignored.If key-marker is specified, multipart uploads whose ObjectName is lexicographically greater than key-marker will be listed, and multipart uploads whose ObjectName is lexicographically equal to key-marker with UploadID greater than upload-id-marker will be listed. | String | No |
// ListMultipartUploadsResult saves ListMultipartUploads resultstype ListMultipartUploadsResult struct {Bucket stringEncodingType stringKeyMarker stringUploadIDMarker stringNextKeyMarker stringNextUploadIDMarker stringMaxUploads intIsTruncated boolUploads []struct {Key stringUploadID stringStorageClass stringInitiator *InitiatorOwner *OwnerInitiated string}Prefix stringDelimiter stringCommonPrefixes []string}// Use the same type as the ownertype Initiator Owner// “Owner” defines the bucket/object's ownertype Owner struct {ID stringDisplayName string}
Parameter | Description | Type |
Bucket | Destination bucket for multipart upload in the format of BucketName , for example, examplebucket-1250000000 | String |
EncodingType | Encoding type of the returned value. The returned value is not encoded by default. Valid value: url | String |
KeyMarker | Specifies the key where the list starts | String |
UploadIDMarker | Specifies the uploadId where the list starts | String |
NextKeyMarker | If the returned list is truncated, the NextKeyMarker returned will be the starting point of the subsequent list | String |
NextUploadIdMarker | If the returned list is truncated, the UploadId returned will be the starting point of the subsequent list | String |
MaxUploads | Maximum number of parts to return at a time. Default value: 1000 | String |
IsTruncated | Indicates whether the returned list is truncated | Bool |
Uploads | Information on each upload | Container |
Key | Object name | String |
UploadID | ID that identifies the current multipart upload | String |
Key | Indicates whether the returned list is truncated | Bool |
StorageClass | Storage class of the parts, such as STANDARD (default), STANDARD_IA , and ARCHIVE . For more information, see Storage Class Overview. | string |
Initiator | Indicates information about the initiator of this upload | Container |
Owner | Indicates information about the owner of these parts | Container |
Initiated | Start time of the multipart upload | String |
Prefix | Specifies that returned object keys must be prefixed with this value. Note that if you use this parameter, returned keys will contain the prefix | Struct |
Delimiter | A symbol. The identical paths between Prefix and the first occurrence of the Delimiter are grouped and defined as a common prefix. If no Prefix is specified, the common prefix starts with the beginning of the path | String |
CommonPrefixes | The identical paths between Prefix and Delimiter are grouped and defined as a common prefix | String |
ID | Unique CAM ID of users | String |
DisplayName | User Identifier (UIN) | String |
uploadId
.func (s *ObjectService) InitiateMultipartUpload(ctx context.Context, name string, opt *InitiateMultipartUploadOptions) (*InitiateMultipartUploadResult, *Response, error)
package mainimport ("context""fmt""github.com/tencentyun/cos-go-sdk-v5""net/http""net/url""os")func main(){// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.// Replace it with your region, which can be viewed in the COS console at https://console.tencentcloud.com/. For more information about regions, visit https://www.tencentcloud.com/document/product/436/6224.u, _ := url.Parse("https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com")b := &cos.BaseURL{BucketURL: u}client := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{// Get the key from environment variables// Environment variable `SECRETID` refers to the user's `SecretId`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.// Environment variable `SECRETKEY` refers to the user's `SecretKey`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretKey: os.Getenv("SECRETKEY"), // User `SecretKey`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.},})name := "exampleobject"// Optional. Considering the ACL limit, we recommend not setting an object ACL when uploading an object unless required. The object will then inherit bucket ACL by default.v, _, err := client.Object.InitiateMultipartUpload(context.Background(), name, nil)if err != nil{panic(err)}UploadID := v.UploadIDfmt.Println(UploadID)}
type InitiateMultipartUploadOptions struct {*ACLHeaderOptions*ObjectPutHeaderOptions}type ACLHeaderOptions struct {XCosACL stringXCosGrantRead stringXCosGrantWrite stringXCosGrantFullControl string}type ObjectPutHeaderOptions struct {CacheControl stringContentDisposition stringContentEncoding stringContentType stringContentLength int64Expires string// Custom x-cos-meta-* headerXCosMetaXXX *http.HeaderXCosStorageClass string}
Parameter | Description | Type | Required |
key | ObjectKey is the unique identifier of an object in a bucket. For example, in the object's access domain name examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/pic.jpg , the ObjectKey is doc/pic.jpg . | String | Yes |
XCosACL | Sets the file ACL, such as private or public-read | String | No |
XCosGrantFullControl | Grants full permission in the format: id="[OwnerUin]" | String | No |
XCosGrantRead | Grants read permission in the format: id="[OwnerUin]" | String | No |
XCosStorageClass | Storage class of the object, such as STANDARD (default), STANDARD_IA , and ARCHIVE . For more information, see Storage Class Overview. | string | No |
Expires | Sets Content-Expires | String | No |
CacheControl | Cache policy. Sets Cache-Control | String | No |
ContentType | Content Type. Sets Content-Type | String | No |
ContentDisposition | Filename. Sets Content-Disposition | String | No |
ContentEncoding | Encoding format. Sets Content-Encoding | String | No |
ContentLength | Sets the length of the request content | Int64 | No |
XCosMetaXXX | User-defined file metadata. It must start with x-cos-meta. Otherwise, it will be ignored | http.Header | No |
type InitiateMultipartUploadResult struct {Bucket stringKey stringUploadID string}
Parameter | Description | Type |
UploadId | ID that identifies the multipart upload | string |
Bucket | Bucket name in the format of BucketName-APPID | string |
Key | Object key, the unique identifier of an object in a bucket. For example, if the object endpoint is examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/pic.jpg , its object key is doc/pic.jpg | string |
Upload Part
) is used to upload an object in parts.func (s *ObjectService) UploadPart(ctx context.Context, key, uploadID string, partNumber int, r io.Reader, opt *ObjectUploadPartOptions) (*Response, error)
package mainimport ("context""fmt""github.com/tencentyun/cos-go-sdk-v5""net/http""net/url""os""strings")func main(){// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.// Replace it with your region, which can be viewed in the COS console at https://console.tencentcloud.com/. For more information about regions, visit https://www.tencentcloud.com/document/product/436/6224.u, _ := url.Parse("https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com")b := &cos.BaseURL{BucketURL: u}client := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{// Get the key from environment variables// Environment variable `SECRETID` refers to the user's `SecretId`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.// Environment variable `SECRETKEY` refers to the user's `SecretKey`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretKey: os.Getenv("SECRETKEY"), // User `SecretKey`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.},})name := "exampleobject"// Optional. Considering the ACL limit, we recommend not setting an object ACL when uploading an object unless required. The object will then inherit bucket ACL by default.v, _, err := client.Object.InitiateMultipartUpload(context.Background(), name, nil)if err != nil{panic(err)}UploadID := v.UploadIDfmt.Println(UploadID)// Note: Up to 10,000 parts can be uploaded.key := "exampleobject"f := strings.NewReader("test hello")// Optionalresp, err := client.Object.UploadPart(context.Background(), key, UploadID, 1, f, nil,)if err != nil{panic(err)}PartETag := resp.Header.Get("ETag")fmt.Println(PartETag)}
type ObjectUploadPartOptions struct {ContentLength int64ContentMD5 string}
Parameter | Description | Type | Required |
key | ObjectKey is the unique identifier of an object in a bucket. For example, in the object's access domain name examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/pic.jpg , the ObjectKey is doc/pic.jpg . | String | Yes |
UploadId | ID that identifies the multipart upload; generated by InitiateMultipartUpload | String | Yes |
PartNumber | Number that identifies the uploaded part | Int | Yes |
r | Content of the uploaded part, which can be a local file stream or an input stream. When r is not bytes.Buffer/bytes.Reader/strings.Reader , opt.ContentLength must be specified | io.Reader | Yes |
ContentLength | Sets the length of the request content | int64 | No |
ContentMD5 | Base64-encoded MD5 checksum of the request body content defined in RFC 1864. This value is a 24-character string, such as ZzD3iDJdrMAAb00lgLLeig== , and is used to verify whether the request body experienced any changes during transfer. | string | No |
{'ETag': 'string'}
resp, err := client.Object.UploadPart(context.Background(), key, UploadID, 1, f, nil)etag := resp.Header.Get("ETag")
Parameter | Description | Type |
ETag | MD5 of the uploaded part | String |
List Parts
) is used to query the uploaded parts of a multipart upload.func (s *ObjectService) ListParts(ctx context.Context, name, uploadID string, opt *ObjectListPartsOptions) (*ObjectListPartsResult, *Response, error)
package mainimport ("context""fmt""github.com/tencentyun/cos-go-sdk-v5""net/http""net/url""os")func main(){// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.// Replace it with your region, which can be viewed in the COS console at https://console.tencentcloud.com/. For more information about regions, visit https://www.tencentcloud.com/document/product/436/6224.u, _ := url.Parse("https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com")b := &cos.BaseURL{BucketURL: u}client := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{// Get the key from environment variables// Environment variable `SECRETID` refers to the user's `SecretId`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.// Environment variable `SECRETKEY` refers to the user's `SecretKey`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretKey: os.Getenv("SECRETKEY"), // User `SecretKey`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.},})key := "exampleobject"v, _, err := client.Object.InitiateMultipartUpload(context.Background(), key, nil)if err != nil{panic(err)}UploadID := v.UploadIDfmt.Println(UploadID)_, _, err := client.Object.ListParts(context.Background(), key, UploadID, nil)if err != nil{panic(err)}}
type ObjectListPartsOptions struct {EncodingType stringMaxParts stringPartNumberMarker string}
Parameter | Description | Type | Required |
key | ObjectKey is the unique identifier of an object in a bucket. For example, in the object's access domain name examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/pic.jpg , the ObjectKey is doc/pic.jpg . | string | Yes |
UploadId | ID that identifies the multipart upload; generated by InitiateMultipartUpload | String | Yes |
EncodingType | Encoding type of the returned value | String | No |
max-parts | Maximum number of parts to return at a time. Default: 1000 | String | No |
PartNumberMarker | The marker after which the returned list begins. By default, entries are listed in UTF-8 binary order. | String | No |
type ObjectListPartsResult struct {Bucket stringEncodingType stringKey stringUploadID stringInitiator *InitiatorOwner *OwnerStorageClass stringPartNumberMarker stringNextPartNumberMarker stringMaxParts stringIsTruncated boolParts []Object}type Initiator struct {UIN stringID stringDisplayName string}type Owner struct {UIN stringID stringDisplayName string}type Object struct {Key stringETag stringSize intPartNumber intLastModified stringStorageClass stringOwner *Owner}
Parameter | Description | Type |
Bucket | Bucket name in the format: BucketName-APPID , for example, examplebucket-1250000000 | String |
EncodingType | Encoding type of the returned value. The returned value is not encoded by default. Valid value: url | String |
Key | Object key, the unique identifier of an object in a bucket. For example, if the object endpoint is examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/pic.jpg , its object key is doc/pic.jpg | string |
UploadId | ID that identifies the multipart upload; generated by InitiateMultipartUpload | String |
Initiator | Initiator of the multipart upload, including DisplayName , UIN and ID | Struct |
Owner | Information on the file owner, including DisplayName , UIN and ID | Struct |
StorageClass | Storage class of the object, such as STANDARD (default), STANDARD_IA , and ARCHIVE . For more information, see Storage Class Overview. | string |
PartNumberMarker | Specifies the part number after which the listing should begin. It defaults to 0, which means the listing begins with the first part | String |
NextPartNumberMarker | Specifies the part number after which the next listing should begin | Int |
MaxParts | Maximum number of parts to return at a time. Default value: 1000 | Int |
IsTruncated | Indicates whether the returned list is truncated | Bool |
Part | Information on the uploaded part, including ETag , PartNumber , Size , and LastModified | Struct |
Complete Multipart Upload
) is used to complete the multipart upload of a file.func (s *ObjectService) CompleteMultipartUpload(ctx context.Context, key, uploadID string, opt *CompleteMultipartUploadOptions) (*CompleteMultipartUploadResult, *Response, error)
package mainimport ("context""fmt""github.com/tencentyun/cos-go-sdk-v5""net/http""net/url""os""strings")func main(){// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.// Replace it with your region, which can be viewed in the COS console at https://console.tencentcloud.com/. For more information about regions, visit https://www.tencentcloud.com/document/product/436/6224.u, _ := url.Parse("https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com")b := &cos.BaseURL{BucketURL: u}client := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{// Get the key from environment variables// Environment variable `SECRETID` refers to the user's `SecretId`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.// Environment variable `SECRETKEY` refers to the user's `SecretKey`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretKey: os.Getenv("SECRETKEY"), // User `SecretKey`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.},})name := "exampleobject"// Optional. Considering the ACL limit, we recommend not setting an object ACL when uploading an object unless required. The object will then inherit bucket ACL by default.v, _, err := client.Object.InitiateMultipartUpload(context.Background(), name, nil)if err != nil{panic(err)}UploadID := v.UploadIDfmt.Println(UploadID)// Note: Up to 10,000 parts can be uploaded.key := "exampleobject"f := strings.NewReader("test hello")// "opt" is optional.resp, err := client.Object.UploadPart(context.Background(), key, UploadID, 1, f, nil,)if err != nil{panic(err)}PartETag := resp.Header.Get("ETag")fmt.Println(PartETag)opt := &cos.CompleteMultipartUploadOptions{}opt.Parts = append(opt.Parts, cos.Object{PartNumber: 1, ETag: PartETag},)_, _, err = client.Object.CompleteMultipartUpload(context.Background(), key, UploadID, opt,)if err != nil{panic(err)}}
type CompleteMultipartUploadOptions struct {Parts []Object}type Object struct {ETag stringPartNumber int}
Parameter | Description | Type | Required |
key | ObjectKey is the unique identifier of an object in a bucket. For example, in the object's access domain name examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/pic.jpg , the ObjectKey is doc/pic.jpg . | String | Yes |
UploadId | ID that identifies the multipart upload; generated by InitiateMultipartUpload | String | Yes |
CompleteMultipartUploadOptions | Information on all parts, including ETag and PartNumber | Struct | Yes |
type CompleteMultipartUploadResult struct {Location stringBucket stringKey stringETag string}
Parameter | Description | Type |
Location | URL | String |
Bucket | Bucket name in the format of BucketName-APPID , for example, examplebucket-1250000000 | String |
Key | Object key, the unique identifier of an object in a bucket. For example, if the object endpoint is examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/pic.jpg , its object key is doc/pic.jpg | string |
ETag | Unique tag of a merged object. This value does not represent the MD5 checksum of the object content, but is used only to verify the uniqueness of the object as a whole. To verify the object content, you can check the ETag of each part during the upload process | String |
Abort Multipart Upload
) is used to abort a multipart upload and delete the uploaded parts.func (s *ObjectService) AbortMultipartUpload(ctx context.Context, key, uploadID string) (*Response, error)
package mainimport ("context""github.com/tencentyun/cos-go-sdk-v5""net/http""net/url""os")func main(){// Bucket name in the format of `BucketName-APPID` (`APPID` is required), which can be viewed in the COS console at https://console.tencentcloud.com/cos5/bucket.// Replace it with your region, which can be viewed in the COS console at https://console.tencentcloud.com/. For more information about regions, visit https://www.tencentcloud.com/document/product/436/6224.u, _ := url.Parse("https://examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com")b := &cos.BaseURL{BucketURL: u}client := cos.NewClient(b, &http.Client{Transport: &cos.AuthorizationTransport{// Get the key from environment variables// Environment variable `SECRETID` refers to the user's `SecretId`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretID: os.Getenv("SECRETID"), // User `SecretId`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.// Environment variable `SECRETKEY` refers to the user's `SecretKey`, which can be viewed in the CAM console at https://console.tencentcloud.com/cam/capi.SecretKey: os.Getenv("SECRETKEY"), // User `SecretKey`. We recommend you use a sub-account key and follow the principle of least privilege to reduce risks. For information about how to obtain a sub-account key, visit https://www.tencentcloud.com/document/product/598/37140?from_cn_redirect=1.},})key := "exampleobject"v, _, err := client.Object.InitiateMultipartUpload(context.Background(), key, nil)if err != nil{panic(err)}UploadID := v.UploadID// Abort_, err = client.Object.AbortMultipartUpload(context.Background(), key, UploadID)if err != nil{panic(err)}}
Parameter | Description | Type | Required |
key | Object key, the unique identifier of an object in a bucket. For example, if the object endpoint is examplebucket-1250000000.cos.ap-guangzhou.myqcloud.com/doc/pic.jpg , its object key is doc/pic.jpg | string | Yes |
UploadId | ID of the multipart upload | String | Yes |
Apakah halaman ini membantu?