从 s3 存储桶 Rails 5 aws-sdk 中删除对象

Delete object from s3 bucket Rails 5 aws-sdk

我是 RoR 的新手。

我已将我的网络应用程序配置为使用 'aws-sdk' gem 将对象上传到 s3。连接正常,对象上传正确。

但是,我很难从 Rails 中删除这些对象。我收到此错误:

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<Error>
<Code>MethodNotAllowed</Code>
<Message>
The specified method is not allowed against this resource.
</Message>
<Method>POST</Method>
<ResourceType>OBJECT</ResourceType>

SONGS_CONTROLLER >

class SongsController < ApplicationController

  def index
    @songs = Song.all
  end

  def create
    #make an object in your bucket for the upload
    file_to_upload = params[:file]
    file_name = params[:file].original_filename
    bucket = S3.bucket(S3_BUCKET.name)

    obj = bucket.object(file_name)
    #byebug

    #upload the file:
    obj.put(
      acl: "public-read",
      body: file_to_upload
      )

    #create an object for the upload
    @song = Song.new(
      url: obj.public_url,
      name: obj.key
      )

    #save the upload
    if @song.save
      redirect_to songs_path, notice: 'File successfully uploaded'
    else
      flash.now[:notice] = 'There was an error'
      render :new
    end
  end

  def delete
    @song = Song.find(params[:file])
    obj = bucket.object(@song.key)
    obj.delete
    @song.destroy
  end

end

INDEX.HTML.RB >

  <% @songs.each do |song| %>
  <ul>
    <%= link_to song.name, song.url %>
    ///
    <%= link_to 'Delete', song.url + song.name, method: :delete, data: {confirm: 'Do you want to delete this song?'} %>
  </ul>
  <% end %>

路线 >

Rails.application.routes.draw do
  get 'songs/index'
  get 'songs/create'
  get 'songs/delete'
  root 'songs#index'
  resources :songs
end

您 运行 遇到的问题很可能是 s3 存储桶上设置的权限,而不是您的代码。您要么需要更改试图删除文件的 aws 用户 permissions on that bucket it self or you have to set up a policy

我在尝试从我的存储桶中删除图片时遇到了类似的问题。 据我所知,尝试将 ACL 更改为 public-read-write。 如果只是public-读取它不会让你修改或删除文件。

当您删除对象时,我遇到了一个问题,在保存后我会像您一样将 link 保存到我数据库中的文件中。当你想删除一个对象时,你只需要密钥。

整个link是这样的:

//bucketname.region.amazonaws.com/folder/3bd8f451-0d6a-496b-94e9-5d53bde998ab/3.jpg

您不能使用那个 link 发出删除请求。您必须提取 link 的密钥。

  def delete_s3_image
    key = self.picture.split('amazonaws.com/')[1]
    S3_BUCKET.object(key).delete
  end

键值将如下所示:

folder/3bd8f451-0d6a-496b-94e9-5d53bde998ab/3.jpg

我把它放在 before_destroy 回调中。

before_destroy :delete_s3_image

我希望这对您或任何其他在从 S3 中删除对象时遇到问题的人有所帮助。

这是我在 S3 中删除对象的最终代码

def delete
    #delete song from DB
    @song = Song.find_by(params[:file])
    @song.destroy
    respond_to do |format|
      format.html { redirect_to songs_path, notice: 'File successfully deleted' and return }
      format.json { head :no_content }
    end
    #delete song from bucket
    bucket = S3.bucket(S3_BUCKET.name)
    obj = bucket.object(params[:song])
    obj.delete

  end