我正在尝试使用适用于Ruby的AWS开发工具包在Rails应用程序中执行某些S3上载,下载和删除操作。上传和下载工作正常;删除不是那么多。我无休止地用谷歌搜索了几个"解决方案,"但它们都没有真正起作用。
我尝试了几种尝试#1的变种。我尝试了delete_objects,尝试传入数组和散列而不是单个对象名,尝试传入key:object name等。
尝试#1:
def delete_file
access_key_id = Rails.configuration.app['access_key_id']
secret_access_key = Rails.configuration.app['secret_access_key']
credentials = Aws::Credentials.new(access_key_id, secret_access_key)
Aws.config[:credentials] = credentials
s3_client = Aws::S3::Client.new(region: Rails.configuration.app['s3_region'], credentials: credentials)
s3_resource = Aws::S3::Resource.new(client: s3_client)
bucket = s3_resource.bucket(Rails.configuration.app['s3_bucket'])
obj = s3_resource.bucket(Rails.configuration.app['s3_bucket']).object(object_name)
s3_response = obj.delete
Rails.logger.error("XXX")
Rails.logger.error(s3_response)
Rails.logger.error("XXX")
return s3_response
end
输出:
XXX
#<struct Aws::S3::Types::DeleteObjectOutput delete_marker=true, version_id="null", request_charged=nil>
XXX
尝试#2:
def delete_file
access_key_id = Rails.configuration.app['access_key_id']
secret_access_key = Rails.configuration.app['secret_access_key']
credentials = Aws::Credentials.new(access_key_id, secret_access_key)
Aws.config[:credentials] = credentials
s3_client = Aws::S3::Client.new(region: Rails.configuration.app['s3_region'], credentials: credentials)
s3_resource = Aws::S3::Resource.new(client: s3_client)
bucket = s3_resource.bucket(Rails.configuration.app['s3_bucket'])
s3_response = bucket.delete_objects({
delete: {
objects: [
{
key: object_name
}
]
}
})
Rails.logger.error("XXX")
Rails.logger.error(s3_response)
Rails.logger.error("XXX")
return s3_response
end
输出:
XXX
#<struct Aws::S3::Types::DeleteObjectsOutput deleted=[#<struct Aws::S3::Types::DeletedObject key="[object_name]?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=[stuff]%2F20170813%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20170813T164341Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=[stuff]", version_id=nil, delete_marker=true, delete_marker_version_id="null">], request_charged=nil, errors=[]>
XXX
请注意,我使用的S3存储桶已关闭版本控制,因此只会有一个版本的上传文件。我想从给定的存储桶中完全删除给定的对象名称。
我正在寻找一种以编程方式在Rails 5.1中执行此操作的方法。谢谢,全部。
编辑:两次尝试不起作用 - 与尝试#1相同的输出:
s3_response = s3_client.delete_object({
bucket: Rails.configuration.app['s3_bucket'],
key: object_name
})
s3_response = s3_client.delete_object({
bucket: Rails.configuration.app['s3_bucket'],
key: full_object_url
})
答案 0 :(得分:0)
您在代码中定义object_name
的位置?此外,如果您只需要与S3存储桶进行交互,我建议您使用更简单的gem:https://github.com/qoobaa/s3
答案 1 :(得分:0)
解决方案是使用更简单的宝石:https://github.com/qoobaa/s3。感谢CV-Gate!