[英]How to access private and public images in the same Ruby on Rails app from s3 using paperclip
The Application 应用程序
I am writing an application that requires getting the pictures from users and saving them in AWS S3 bucket. 我正在编写一个需要从用户那里获取图片并将其保存在AWS S3存储桶中的应用程序。
app/models/picture.rb app / models / picture.rb
class Picture < ActiveRecord::Base
include Paperclip::Glue
belongs_to :user
scope :active_objects, -> { where(is_deleted: false)}
has_attached_file :image,
:styles => {:medium => "800>", :small => "480>", :thumb => "100>"},
:convert_options => {:medium =>'-quality 90', :small =>'-quality 80', :thumb => '-quality 50' },
:storage => :s3,
:url => ":s3_domain_url",
:path => 'pictures/:id/image/:style/:basename.:extension',
# :s3_permissions => :private,
:s3_region => 's3-ap-southeast-1.amazonaws.com',
:s3_endpoint => 's3-ap-southeast-1.amazonaws.com',
:s3_credentials => Proc.new { |a| a.instance.s3_credentials }
def s3_credentials
{:bucket => App.secrets.bucket_name, :access_key_id => App.secrets.aws_access_key_id,
:secret_access_key => App.secrets.aws_secret_access_key}
end
def url(style_name = :original, time = 30.minutes.to_i)
image.s3_permissions == :private ? (image.expiring_url(time, style_name)) : (image.url(style_name))
end
end
Problem 问题
As you can see, I had set s3_permissions to true and for accessing those pictures I used expiring_url method. 如您所见,我已经将s3_permissions设置为true,并且为了访问那些图片使用了expiring_url方法。 Now, I want to make the pictures public so I commented s3_permissions.
现在,我想将图片公开,所以我评论了s3_permissions。
After uploading a new picture, I could access the picture without using the expiring_url method 上传新图片后,无需使用expiring_url方法就可以访问图片
>> Picture.last.url
and the url in the response opens up an image in browser tab but still the images that had been uploaded earlier (Picture.first) are not accessible. 并且响应中的url在“浏览器”选项卡中打开了一个图像,但是仍然无法访问之前上传的图像(Picture.first)。 When I try to open the url, it gives me this
当我尝试打开网址时,它给了我这个
<Error>
<Code>AccessDenied</Code>
<Message>Access Denied</Message>
<RequestId>6423906A78A3FDFF</RequestId>
<HostId>
fowfNEi6+mM265iGig+jhT1/ih2P7yhPzNegHiS9Q6NrP4mnGNKkXFDefLva85tjAQ0uNbenYew=
</HostId>
</Error>
Also, their s3_permissions are coming as public_read. 同样,它们的s3_permissions作为public_read来。
>> Picture.first.image.s3_permissions
A, [2018-05-01T01:18:05.171381 #94266] ANY -- : 2018-05-01 01:18:05 +0530 severity=DEBUG, Picture Load (0.7ms) SELECT "pictures".* FROM "pictures" ORDER BY "pictures"."id" ASC LIMIT $1 [["LIMIT", 1]]
=> :public_read
You have to configure this access on the S3 side. 您必须在S3端配置此访问权限。
Put this in your bucket policy: 将其放入您的存储桶策略中:
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::your_bucket_name/*"
}
]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.