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

Rails aws-sdk cannot delete file on Amazon S3

我的代码没有删除我的 Amazon S3 存储桶中的文件,我不知道为什么。

日志

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"}

图物控制器

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

class Picturething < ActiveRecord::Base
  validates  :picture, presence: true
  .
  .
end

在视图中

<%= 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 %>

初始化器

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'])

rails 位工作正常 - 图片从 rails 数据库中删除没问题。但是图片还在亚马逊的桶里。

成功了。我提交的是 url 而不是密钥。密钥是通过切掉主机位从 url 获得的:

图物控制器

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