This topic describes how to use the OSS Ruby SDK to access OSS services to view the bucket list and object list, to upload, download, and delete the objects.
For usage convenience, the following operations are performed in irb
which is Ruby’s interactive command-line interface (CLI).
Initialize the client
Input the following content on the CLI and press the Enter:
irb
Enter the Ruby interactive CLI mode. Introduce the SDK package with require
:
> require 'aliyun/oss'
=> true
>
symbol introduces the command that the user enters, and the =>
symbol introduces the content returned by a program.
Run the following command to create an OSSClient:
> client = Aliyun::OSS::Client.new(
> endpoint: 'endpoint',
> access_key_id: 'AccessKeyId',
> access_key_secret: 'AccessKeySecret')
=> #<Aliyun::OSS::Client...
Replace the parameters with the actual endpoint, AccessKeyID, and AccessKeySecret.
View the bucket list
Run the following command to view the bucket list:
> buckets = client.list_buckets
=> #<Enumerator...
> buckets.each { |b| puts b.name }
=> bucket-1
=> bucket-2
=> ...
If the bucket list is empty, run the following command to create a bucket:
> client.create_bucket('my-bucket')
=> true
- For bucket naming conventions, see Basic OSS Concepts.
- The bucket name cannot be the same with existing bucket names of other users in OSS. To create a bucket successfully, select a unique bucket name.
View the object list
You can run the following command to view the objects in a bucket:
> bucket = client.get_bucket('my-bucket')
=> #<Aliyun::OSS::Bucket...
> objects = bucket.list_objects
=> #<Enumerator...
> objects.each { |obj| puts obj.key }
=> object-1
=> object-2
=> ...
Upload an object
You can run the following command to upload a file to a bucket:
> bucket.put_object('my-object', :file => 'local-file')
=> true
Specifically, local-file
indicates the path to the local file to be uploaded. When the file is uploaded, you
can view it using list_objects
:
> objects = bucket.list_objects
=> #<Enumerator...
> objects.each { |obj| puts obj.key }
=> my-object
=> ...
Download an object
You can run the following command to download an object from a bucket:
> bucket.get_object('my-object', :file => 'local-file')
=> #<Aliyun::OSS::Object...
Specifically, local-file
is the path to the downloaded object. After the object is downloaded, you can open
the object to view its content.
Delete an object
You can run the following command to delete an object from a bucket:
> bucket.delete_object('my-object')
=> true
After deletion, you can run list_objects
to check whether the object has been successfully deleted from the bucket.
> objects = bucket.list_objects
=> #<Enumerator...
> objects.each { |obj| puts obj.key }
=> object-1
=> ...