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.
Precautions
The sample code in this topic uses the region ID
cn-hangzhou
of China (Hangzhou) as an example and uses the public endpoint by default. If you want to access OSS from other Alibaba Cloud services in the same region as OSS, use the internal endpoint. For more information about the mapping between regions and endpoints supported by OSS, see OSS regions and endpoints.In this topic, access credentials obtained from environment variables are used. For more information about how to configure 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 Policy or Bucket Policy.
API | Action | Definition |
PutObject |
| Uploads an object. |
| When uploading an object, if you specify object tags through x-oss-tagging, this permission is required. | |
| When uploading an object, if the object metadata contains X-Oss-Server-Side-Encryption: KMS, these two permissions are required. | |
|
Method definition
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)
The API name | Anomaly description |
Client.PutObject | Perform simple upload to upload an object that is up to 5 GiB in size. Support CRC-64 (enabled by default). Progress Bar Support 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 reuploaded. |
Client.PutObjectFromFile | Provide the same capability as Client.PutObject. Obtain the request body from the path of the local file. |
Request parameters
Parameter | Type | Note |
ctx | context.Context | The context of the request, which can be used to specify the total duration of the request. |
request | *PutObjectRequest | Set the request parameters for the specific operation, such as the access control list (Acl) of the object, whether to forbid overwriting (ForbidOverwrite), and custom metadata (Metadata). For more information, see PutObjectRequest. |
optFns | ...func(*Options) | (Optional) The configuration parameters at the operation level. For more information, see Options. |
Response parameters
Parameter | Type | Note |
result | *PutObjectResult | The return value of the operation. This parameter is valid when the value of err is nil. For more information, see PutObjectResult. |
err | error | The status of the request. If the request fails, the value of err is not nil. |
Sample code
The following sample code demonstrates 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"
)
// Define 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.
)
// Use the init function 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 the command line arguments.
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 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 OSS client.
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), // The name of the bucket.
Key: oss.Ptr(objectName), // The name of the object.
StorageClass: oss.StorageClassStandard, // Set the storage class of the object to Standard.
Acl: oss.ObjectACLPrivate, // Set the ACL of the object to private.
Metadata: map[string]string{
"yourMetadataKey1": "yourMetadataValue1", // 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, see the GitHub examples put_object.go and put_object_from_file.go.
For more information about the API operations for simple upload, see PutObject and PutObjectFromFile.