Upload objects using OSS SDK for Go 2.0
This topic describes how to upload objects to a versioned bucket using OSS SDK for Go 2.0.
Usage notes
-
The sample code in this topic uses the region ID
cn-hangzhouof the China (Hangzhou) region. By default, a public endpoint is used to access resources in a bucket. If you want to access resources in the bucket from other Alibaba Cloud services in the same region in which the bucket is located, use an internal endpoint. For more information about supported regions and endpoints, see Regions and endpoints. -
In this topic, access credentials are obtained from environment variables. For more information about how to configure the access credentials, see Configure access credentials.
-
To upload a file, you must have the
oss:PutObjectpermission. For more information, see Grant a custom policy.
Sample code
Simple upload
-
If you upload an object to a versioning-enabled bucket, OSS generates a unique version ID for the object and includes the version ID in the x-oss-version-id response header.
-
If you upload an object to a versioning-suspended bucket, the version ID generated for the object is null. If you upload an object with the same name as an existing object to a versioning-suspended bucket, the existing object is overwritten. This way, each object has only a single version whose version ID is null.
The following sample code performs a simple upload:
package main
import (
"context"
"flag"
"log"
"strings"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Specify the global variables.
var (
region string // The region in which the bucket is located.
bucketName string // The name of the bucket.
objectName string // The name of the object.
)
// Define the init function used to initialize parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
flag.StringVar(&objectName, "object", "", "The name of the object.")
}
func main() {
// Parse command line parameters.
flag.Parse()
// Check whether the bucket name is empty.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is empty.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check whether the object name is empty.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Specify the content that you want to upload.
content := "hi oss"
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSS client.
client := oss.NewClient(cfg)
// Create a request to upload an object.
request := &oss.PutObjectRequest{
Bucket: oss.Ptr(bucketName), // The name of the bucket.
Key: oss.Ptr(objectName), // The name of the object.
Body: strings.NewReader(content), // The content that you want to upload.
}
// Execute the request to upload an object.
result, err := client.PutObject(context.TODO(), request)
if err != nil {
log.Fatalf("failed to put object %v", err)
}
// Display the version ID of the object.
log.Printf("put object result versionId:%#v\n", *result.VersionId)
}
Append upload
In a versioned bucket, the AppendObject operation can be performed only on the current version of an appendable object.
-
When you perform the AppendObject operation on the current version of an appendable object, OSS does not generate a previous version for the object.
-
When you perform the PutObject or DeleteObject operation on the current version of an appendable object, OSS saves the appendable object as a previous version that cannot be appended anymore.
-
The AppendObject operation cannot be performed on the current version of a non-appendable object such as a normal object or a delete marker.
The following sample code performs an append upload:
package main
import (
"context"
"flag"
"log"
"strings"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define the global variables.
var (
region string
bucketName string
objectName string
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
flag.StringVar(&objectName, "object", "", "The name of the object.")
}
func main() {
// Parse command line parameters.
flag.Parse()
// Specify the position from which the append operation starts.
var (
position = int64(0)
)
// Check whether the bucket name is specified.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check whether the region is specified.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check whether the object name is specified.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSSClient instance.
client := oss.NewClient(cfg)
// Specify the content that you want to append.
content := "hi append object"
// Create an AppendObject request to perform the first append operation.
request := &oss.AppendObjectRequest{
Bucket: oss.Ptr(bucketName),
Key: oss.Ptr(objectName),
Position: oss.Ptr(position),
Body: strings.NewReader(content),
Tagging: oss.Ptr("tag1=value1&tag2=value2"), // Configure tags for the object.
}
// Execute the first AppendObject request and process the result.
// The first time an object is appended, the append operation starts at 0. The position for the next append operation is included in the response.
result, err := client.AppendObject(context.TODO(), request)
if err != nil {
log.Fatalf("failed to append object %v", err)
}
// Create an AppendObject request to perform the second append operation.
request = &oss.AppendObjectRequest{
Bucket: oss.Ptr(bucketName),
Key: oss.Ptr(objectName),
Position: oss.Ptr(result.NextPosition), // Obtain the value of the NextPosition parameter from the response to the first AppendObject request.
Body: strings.NewReader("hi append object"),
}
// Execute the AppendObject request and process the result.
result, err = client.AppendObject(context.TODO(), request)
if err != nil {
log.Fatalf("failed to append object %v", err)
}
// Log the version ID of the appended object.
log.Printf("append object result:%#v\n", *result.VersionId)
}
Multipart upload
If you call the CompleteMultipartUpload operation to combine the parts into a complete object in a versioned bucket, OSS generates a unique version ID for the object and returns the version ID as the value of the x-oss-version-id header in the response.
Below is the sample code for multipart upload:
package main
import (
"bufio"
"bytes"
"context"
"flag"
"io"
"log"
"os"
"sync"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define the global variables.
var (
region string // The region in which the bucket is located.
bucketName string // The name of the source bucket.
objectName string // The name of the source object.
)
// Specify the init function used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the source bucket.")
flag.StringVar(&objectName, "object", "", "The name of the source object.")
}
func main() {
// Parse command line parameters.
flag.Parse()
// Specify the upload ID.
var uploadId string
// Check whether the source bucket name is specified.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, source bucket name required")
}
// Check whether the region is specified.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check whether the source object name is specified.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, source object name required")
}
// Load the default configurations and specify the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region)
// Create an OSSClient instance.
client := oss.NewClient(cfg)
// Create a request to initiate the multipart upload task.
initRequest := &oss.InitiateMultipartUploadRequest{
Bucket: oss.Ptr(bucketName),
Key: oss.Ptr(objectName),
}
initResult, err := client.InitiateMultipartUpload(context.TODO(), initRequest)
if err != nil {
log.Fatalf("failed to initiate multipart upload %v", err)
}
// Display the result.
log.Printf("initiate multipart upload result:%#v\n", *initResult.UploadId)
uploadId = *initResult.UploadId
// Initialize the wait group and mutex.
var wg sync.WaitGroup
var parts []oss.UploadPart
count := 3
var mu sync.Mutex
// Read data from the local file to the memory and replace yourLocalFile with the actual path of the local file that contains the file name.
file, err := os.Open("yourLocalFile")
if err != nil {
log.Fatalf("failed to open local file %v", err)
}
defer file.Close()
bufReader := bufio.NewReader(file)
content, err := io.ReadAll(bufReader)
if err != nil {
log.Fatalf("failed to read local file %v", err)
}
log.Printf("file size: %d\n", len(content))
// Calculate the size of each part.
chunkSize := len(content) / count
if chunkSize == 0 {
chunkSize = 1
}
// Start multiple goroutines for the multipart upload task.
for i := 0; i < count; i++ {
start := i * chunkSize
end := start + chunkSize
if i == count-1 {
end = len(content)
}
wg.Add(1)
go func(partNumber int, start, end int) {
defer wg.Done()
// Create the multipart upload request.
partRequest := &oss.UploadPartRequest{
Bucket: oss.Ptr(bucketName), // The name of the bucket.
Key: oss.Ptr(objectName), // The name of the object.
PartNumber: int32(partNumber), // The part number.
UploadId: oss.Ptr(uploadId), // The upload ID.
Body: bytes.NewReader(content[start:end]), // The content of the part.
}
// Send the multipart upload request.
partResult, err := client.UploadPart(context.TODO(), partRequest)
if err != nil {
log.Fatalf("failed to upload part %d: %v", partNumber, err)
}
// Capture the result.
part := oss.UploadPart{
PartNumber: partRequest.PartNumber,
ETag: partResult.ETag,
}
// Use a mutex to protect shared data.
mu.Lock()
parts = append(parts, part)
mu.Unlock()
}(i+1, start, end)
}
// Wait until all goroutines are complete.
wg.Wait()
// Complete the multipart upload task.
request := &oss.CompleteMultipartUploadRequest{
Bucket: oss.Ptr(bucketName),
Key: oss.Ptr(objectName),
UploadId: oss.Ptr(uploadId),
CompleteMultipartUpload: &oss.CompleteMultipartUpload{
Parts: parts,
},
}
result, err := client.CompleteMultipartUpload(context.TODO(), request)
if err != nil {
log.Fatalf("failed to complete multipart upload %v", err)
}
// Log the version ID returned from the completed multipart upload operation.
log.Printf("complete multipart upload result versionId:%#v\n", *result.VersionId)
}
References
-
For more information about the API operation for performing simple upload, see PutObject.
-
For more information about the API operation for performing append upload, see AppendObject.
-
For more information about the API operations that you can call to perform multipart upload, see InitiateMultipartUpload, UploadPart and CompleteMultipartUpload.