简体   繁体   English

Rails aws-sdk无法删除Amazon S3上的文件

[英]Rails aws-sdk cannot delete file on Amazon S3

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. rails位工作正常-图片从rails数据库删除没有问题。 But the picture remains in the amazon bucket. 但是图片仍然保留在亚马逊桶中。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM