My code does not delete the file in my Amazon S3 bucket and I don't know why.
我的代码不会删除我的Amazon S3存储桶中的文件,我不知道为什么。
Logs
日志
Processing by PicturethingsController#destroy as HTML
Parameters: {
"authenticity_token"=>"eEmuCyMmV8K3X5xp4rCozbwv8EnU6bZY3+juwBr/v8ScPCP/nbQ5+pgXWZOJkuJ3ZNrfDaNTx86ailFKjwTLCw==",
"picid"=>"10",
"picture_url"=>"//websmash.s3.amazonaws.com/uploads/faa8c7d2-0261-4753-9cbb-c4ea06520721/picture1.png"}
Picturethings controller
Picturethings控制器
before_action :delete_picture_from_s3, only: [:destroy]
before_action :set_s3_direct_post, only: [:edit]
def destroy
@picturething = Picturething.find(params[:picid])
@picturething.destroy # this works fine
redirect_to request.referrer || root_url
end
def delete_picture_from_s3
S3_BUCKET.object(params[:picture_url]).delete
return true
rescue => e
# Do nothing. Leave the now defunct file sitting in the bucket.
return true
end
private
def set_s3_direct_post
@s3_direct_post = S3_BUCKET.presigned_post(key: "uploads/#{SecureRandom.uuid}/${filename}", success_action_status: '201', acl: 'public-read')
end
picturething.rb
picturething.rb
class Picturething < ActiveRecord::Base
validates :picture, presence: true
.
.
end
In the view
在视图中
<%= button_to delete_picture_path(
params: {
picid: standardpicture.id,
picture_url: standardpicture.picture
}
),
class: 'btn btn-default btn-xs',
data: { confirm: "Delete picture: are you sure?" },
method: :delete do %>
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
<% end %>
initializer
初始化
Aws.config.update({
region: 'us-east-1',
credentials: Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY']),
})
S3_BUCKET = Aws::S3::Resource.new.bucket(ENV['S3_BUCKET'])
The rails bit works fine - the picture is deleted from the rails database no problem. But the picture remains in the amazon bucket.
rails bit工作正常 - 图片从rails数据库中删除没问题。但照片仍然在亚马逊桶中。
1 个解决方案
#1
1
Got it working. I was submitting the url rather than the key. The key is obtained from the url by slicing off the host bit:
搞定了。我提交了网址而不是密钥。通过切掉主机位从URL获取密钥:
Picturethings controller
Picturethings控制器
def delete_picture_from_s3
key = params[:picture_url].split('amazonaws.com/')[1]
S3_BUCKET.object(key).delete
return true
rescue => e
# Do nothing. Leave the now defunct file sitting in the bucket.
return true
end
#1
1
Got it working. I was submitting the url rather than the key. The key is obtained from the url by slicing off the host bit:
搞定了。我提交了网址而不是密钥。通过切掉主机位从URL获取密钥:
Picturethings controller
Picturethings控制器
def delete_picture_from_s3
key = params[:picture_url].split('amazonaws.com/')[1]
S3_BUCKET.object(key).delete
return true
rescue => e
# Do nothing. Leave the now defunct file sitting in the bucket.
return true
end