我是RoR的新手。
我已经配置了我的webapp,使用' aws-sdk'将对象上传到s3。宝石。连接运行正常,对象上传正确。
但是,我很难从Rails中删除这些对象。我收到这个错误:
vcl 4.0;
import std;
#other stuff
sub vcl_synth {
if (resp.status == 404) {
set resp.http.Content-Type = "text/html;";
synthetic(std.fileread("/etc/varnish/404.html"));
return (deliver);
}
}
SONGS_CONTROLLER>
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>
INDEX.HTML.RB&gt;
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
路线&gt;
<% @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 %>
答案 0 :(得分:2)
我有一个类似的问题,试图从我的桶中删除图片。 据我所知,尝试将ACL更改为public-read-write。 如果它只是公开阅读,它将不允许您修改或删除该文件。
当你删除对象时,我遇到了一个问题,保存后我会像你一样将链接保存到我的数据库中。如果要删除对象,只需要密钥。
整个链接如下所示:
//bucketname.region.amazonaws.com/folder/3bd8f451-0d6a-496b-94e9-5d53bde998ab/3.jpg
您无法使用该链接发出删除请求。您必须提取该链接的密钥。
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中删除对象时遇到问题的人。
答案 1 :(得分:0)
您遇到的问题很可能是使用s3
存储桶而非您的代码设置的权限。您需要自行更改该存储桶上的permissions,或者您必须设置一个policy,该用户正在尝试删除该文件。
答案 2 :(得分:0)
这是我在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