我有一个使用Rails 5.1开发的博客页面。一切正常,除了在生产中创建帖子并附加图像之后,图像会在一段时间(例如30分钟)后停止显示。我在互联网上搜寻解决方案,发现this表示问题与每次重新启动应用程序后擦除Heroku有关。提供的一种解决方案是将图像托管在Amazon S3之类的服务上。
但是,博客文章图像仍然消失。我需要帮助,因为我无法弄清自己的缺失。以下是相关代码:
shrine.rb:
require "shrine"
require "shrine/storage/s3"
s3_options = {
access_key_id: ENV['S3_KEY'],
secret_access_key: ENV['S3_SECRET'],
region: ENV['S3_REGION'],
bucket: ENV['S3_BUCKET'],
}
if Rails.env.development?
require "shrine/storage/file_system"
Shrine.storages = {
cache: Shrine::Storage::FileSystem.new("public", prefix: "uploads/cache"), # temporary
store: Shrine::Storage::FileSystem.new("public", prefix: "uploads/store") # permanent
}
elsif Rails.env.test?
require 'shrine/storage/memory'
Shrine.storages = {
cache: Shrine::Storage::Memory.new,
store: Shrine::Storage::Memory.new
}
else
require "shrine/storage/s3"
Shrine.storages = {
cache: Shrine::Storage::S3.new(prefix: "cache", **s3_options),
store: Shrine::Storage::S3.new(prefix: "store", **s3_options)
}
end
Shrine.plugin :activerecord # or :activerecord
Shrine.plugin :cached_attachment_data # for retaining the cached file across form redisplays
gemfile:
....................................
# A rich text editor for everyday writing
gem 'trix', '~> 0.11.1'
# a toolkit for file attachments in Ruby applications
gem 'shrine', '~> 2.11'
# Tag a single model on several contexts, such as skills, interests, and awards
gem 'acts-as-taggable-on', '~> 6.0'
# frameworks for multiple-provider authentication.
gem 'omniauth-facebook'
gem 'omniauth-github'
# Simple Rails app key configuration
gem "figaro"
..............................
我使用Figaro gem掩盖环境文件。由于S3存储桶响应,它们很好,而且我已经在博客上启动并运行了OmniAuth。
这是在chrome控制台上显示的图片错误:
我真的需要帮助来启动和运行此博客。谢谢您的宝贵时间。
答案 0 :(得分:3)
默认情况下,Shrine会生成过期的S3 URL,因此很有可能缓存了生成的URL,一旦URL过期,图像就变得不可用。
作为一种解决方法,您可以使S3上传成为公开的,并生成公共URL。您可以通过告诉S3存储将上传设为公开(请注意,这只会影响新的上传,现有的上传将保持私有,因此您必须以其他方式将其公开)来做到这一点,并默认生成公共网址,通过更新初始化程序:
# ...
require "shrine/storage/s3"
Shrine.storages = {
cache: Shrine::Storage::S3.new(prefix: "cache", upload_options: { acl: "public-read" }, **s3_options),
store: Shrine::Storage::S3.new(prefix: "store", upload_options: { acl: "public-read" }, **s3_options)
}
# ...
Shrine.plugin :default_url_options, cache: { public: true }, store: { public: true }
# ...