You can delete a single object, multiple specified objects, objects whose names contain a specific prefix, or delete a specific directory and all objects in the directory.
Warning
- Objects cannot be restored after they are deleted. Exercise caution when you perform this operation.
To maintain OSS-HDFS stability and prevent data loss, do not delete objects from the
.dlsdata/directory.
Delete a single file
The following sample code provides an example on how to delete an object named exampleobject.txt from a bucket named examplebucket:
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
# Set Endpoint to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
# Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
access_key_id: ENV['OSS_ACCESS_KEY_ID'],
access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Set the bucket name. For example, examplebucket.
bucket = client.get_bucket('examplebucket')
# Set the full path of the object. For example, exampledir/exampleobject.txt. The full path cannot contain the bucket name.
bucket.delete_object('exampledir/exampleobject.txt') Batch delete files
The following sample code provides an example on how to delete multiple objects with specified names:
require 'aliyun/oss'
client = Aliyun::OSS::Client.new(
# Set Endpoint to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Endpoint to https://oss-cn-hangzhou.aliyuncs.com.
endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
# Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
access_key_id: ENV['OSS_ACCESS_KEY_ID'],
access_key_secret: ENV['OSS_ACCESS_KEY_SECRET']
)
# Set the bucket name. For example, examplebucket.
bucket = client.get_bucket('examplebucket')
# Set the full paths of the objects to delete. The full paths cannot contain the bucket name.
objs = ['my-object-1', 'my-object-2']
result = bucket.batch_delete_objects(objs)
# By default, the successfully deleted objects are returned.
puts result #['my-object-1', 'my-object-2']
objs = ['my-object-3', 'my-object-4']
result = bucket.batch_delete_objects(objs, :quiet => true)
# The deletion result is not returned.
puts result #[] References
For more information about deleting a single object, see the DeleteObject API operation.
For more information about deleting multiple objects, see the DeleteMultipleObjects API operation.