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.
Usage notes
The sample code in this topic uses the region ID
cn-hangzhou
of 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.
To perform simple upload, you must have the
oss:PutObject
permission. For more information, see Attach a custom policy to a RAM user.
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 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 | 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 Expires, 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
Upload a string
Upload a byte array
Upload a file stream
Upload a network stream
Use the progress bar during object upload
Configure a callback when you upload a local file
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.