2

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

但是,我已经设置了 S3,并且图像被发送到如下所示的存储桶: 在此处输入图像描述

但是,博客文章图像仍然消失。我需要帮助,因为我无法弄清楚我错过了什么。以下是相关代码:

神社.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

宝石文件:

....................................
# 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 控制台上显示的错误:

在此处输入图像描述

我真的需要帮助来启动和运行这个博客。感谢您的时间。

4

1 回答 1

4

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

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

# ...

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 }

# ...
于 2018-07-05T18:11:47.643 回答