Simple upload using OSS SDK for Go 2.0
This topic describes how to quickly upload local files to Object Storage Service (OSS) by using simple upload. This method is simple and suitable for scenarios in which you want to quickly upload local files.
Notes
-
The sample code in this topic uses the region ID
cn-hangzhouof the China (Hangzhou) region. By default, the public endpoint is used to access resources in a bucket. If you want to access resources in the bucket by using other Alibaba Cloud services in the same region in which the bucket is located, use the internal endpoint. For more information about OSS 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.
Permissions
By default, an Alibaba Cloud account has full permissions. RAM users or RAM roles under an Alibaba Cloud account do not have any permissions by default. The Alibaba Cloud account or account administrator must grant operation permissions through RAM policies or Bucket Policy.
|
API |
Action |
Description |
|
PutObject |
|
Uploads an object. |
|
|
Required if you specify object tags by using the |
|
|
|
Required if the |
|
|
|
Method
func (c *Client) PutObject(ctx context.Context, request *PutObjectRequest, optFns ...func(*Options)) (*PutObjectResult, error)
func (c *Client) PutObjectFromFile(ctx context.Context, request *PutObjectRequest, filePath string, optFns ...func(*Options)) (*PutObjectResult, error)
|
Operation |
Description |
|
Client.PutObject |
Perform simple upload to upload an object that is up to 5 GiB in size. Support CRC-64 (enabled by default). Display the progress of an upload task in the progress bar. Support the request body whose type is io.Reader. If the type of the request body is io.Seeker, when the upload task fails, the object is re-uploaded. |
|
Client.PutObjectFromFile |
Provide the same capability as Client.PutObject. Obtain the request body from the path of the local file. |
Request parameters
|
Parameter |
Type |
Description |
|
ctx |
context.Context |
The context of the request, which can be used to specify the total duration of the request. |
|
request |
*PutObjectRequest |
The parameters of a specific API operation, such as Acl, ForbidOverwrite, and Metadata. For more information, visit PutObjectRequest. |
|
optFns |
...func(*Options) |
Optional. The operation-level parameter. For more information, visit Options. |
Response parameters
|
Parameter |
Type |
Description |
|
result |
*PutObjectResult |
The response to the operation. This parameter is valid when the value of err is nil. For more information, visit PutObjectResult. |
|
err |
error |
The status of the request. If the request fails, the value of err cannot be nil. |
Examples
The following sample code provides an example on how to upload a local file to a specific bucket:
package main
import (
"context"
"flag"
"log"
"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.
)
// 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()
// 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")
}
// 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 path of the local file that you want to upload. Example: /Users/localpath/exampleobject.txt.
localFile := "/Users/localpath/exampleobject.txt"
// Create a request to upload the local file.
putRequest := &oss.PutObjectRequest{
Bucket: oss.Ptr(bucketName), // Specify the name of the bucket.
Key: oss.Ptr(objectName), // Specify the name of the object.
StorageClass: oss.StorageClassStandard, // Set the storage class of the object to Standard.
Acl: oss.ObjectACLPrivate, // Set the access control list (ACL) of the object to private.
Metadata: map[string]string{
"yourMetadataKey 1": "yourMetadataValue 1", // Specify the metadata of the object.
},
}
// Execute the request to upload the local file.
result, err := client.PutObjectFromFile(context.TODO(), putRequest, localFile)
if err != nil {
log.Fatalf("failed to put object from file %v", err)
}
// Display the result of the object upload operation.
log.Printf("put object from file result:%#v\n", result)
}
Common scenarios
References
-
For the complete sample code for simple upload, visit put_object.go and put_object_from_file.go.
-
For more information about the API operations that you can call to perform simple upload, visit PutObject and PutObjectFromFile.