Heroku、Shrine 和 Amazon S3:博客 post 图片会在一段时间后消失

Heroku, Shrine and Amazon S3: Blog post Images disappear after some time

我有一个使用 rails 5.1 开发的博客页面。一切正常,除了我在生产中创建 post 并附加图像后,图像会在一段时间后停止显示(比如 30 分钟)。我在互联网上搜寻解决方案并看到 this 这表明问题与 Heroku 在每次应用程序重新启动后擦除目录有关。提供的一种解决方案是将图像托管在 Amazon S3 等服务上。

不过,我已经设置了 S3,图像正在发送到如下所示的存储桶中:

但是,博客 post 图片仍然消失了。我需要帮助,因为我不知道我错过了什么。以下是相关代码:

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

gem文件:

....................................
# 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 来屏蔽 env 文件。它们很好,因为 S3 存储桶有响应,而且我已经启动了 OmniAuth 并在博客上 运行。

这是在图像的 chrome 控制台上显示的错误:

我真的需要帮助来建立这个博客 运行。谢谢你的时间。

Shrine 默认生成过期的 S3 URLs,因此生成的 URLs 可能以某种方式被缓存,然后一旦 URL 过期图像就变得不可用.

作为解决方法,您可以进行 S3 上传 public 并生成 public URL。您可以通过告诉 S3 存储进行上传 public 来做到这一点(请注意,这只会影响新上传,现有上传将保持私有状态,因此您必须以另一种方式进行上传 public),并通过更新初始化程序默认生成 public URLs:

# ...

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 }

# ...