URI :: InvalidURIError(错误的URI(不是URI?):无)Active Storage service_url

问题描述 投票:1回答:1

配置信息

rails version 6.0
ruby version 2.7.0
gem 'image_processing', '~> 1.2'

storage.yml

local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

development.rb

config.active_storage.service = :local
Rails.application.routes.default_url_options[:host] = 'localhost:3000'
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

仅当我使用service= :local时才会出现此异常。使用:amazon时可以正常工作。

user.rb模型

  has_one_attached :avatar

  #throwing exception
  def avatar_urls
    {
      original: avatar.service_url
    } if avatar.attachment
  end

访问avatar_urls时,将引发异常(URI::InvalidURIError (bad URI(is not URI?): nil))。但是,如果我将avatars_url方法更改为以下方法,则可以正常工作。

  #working method
  def avatar_urls
    {
      thumbnail: url_for(avatar.variant(resize: "100x100").processed)
    } if avatar.attachment
  end

这里是痕迹:

Disk Storage (5056.7ms) Generated URL for file at key: variants/i5w1ie6ro07mib4qcdn30lmik6wn/2a7fa5dad6ac227a16e961cbd12ca6f35f1d7947f56a97754d5e22c1a0fd3372 ()
cb_app_container | Completed 500 Internal Server Error in 9523ms (ActiveRecord: 580.9ms | Allocations: 1185509)
cb_app_container | URI::InvalidURIError (bad URI(is not URI?): nil):
cb_app_container | app/models/user.rb:53:in `avatar_urls'
cb_app_container | app/models/user.rb:27:in `user_json'
cb_app_container | app/controllers/api/v1/users_controller.rb:13:in `update'
cb_app_container | [ActiveJob] [ActiveStorage::AnalyzeJob] [33448db4-cf54-4677-906c-06b59f1579ee]    (61.6ms)  BEGIN
cb_app_container | [ActiveJob] [ActiveStorage::AnalyzeJob] [33448db4-cf54-4677-906c-06b59f1579ee]   ActiveStorage::Blob Update (10.3ms)  UPDATE "active_storage_blobs" SET "metadata" = $1 WHERE "active_storage_blobs"."id" = $2  [["metadata", "{\"identified\":true,\"width\":1952,\"height\":3264,\"analyzed\":true}"], ["id", 45]]
cb_app_container | [ActiveJob] [ActiveStorage::AnalyzeJob] [33448db4-cf54-4677-906c-06b59f1579ee]    (19.6ms)  COMMIT
cb_app_container | [ActiveJob] [ActiveStorage::AnalyzeJob] [33448db4-cf54-4677-906c-06b59f1579ee] Performed ActiveStorage::AnalyzeJob (Job ID: 33448db4-cf54-4677-906c-06b59f1579ee) from Async(default) in 6916.06ms
ruby-on-rails rails-activestorage ruby-on-rails-6
1个回答
0
投票

您不应该使用service_url方法在视图中为用户显示图像。根据文档:

返回服务上Blob的URL。该URL旨在出于安全性的考虑而短暂存在,不能直接与用户一起使用。相反,应仅将service_url公开为来自稳定的,可能经过身份验证的URL。将service_url隐藏在重定向还使您无需更改服务即可更改服务更新所有网址。而且它允许重定向到的永久URL要在视图中缓存的service_url。

在使用:amazon的生产环境中,请注意,如果您复制由url_for(avatar.variant(resize: "100x100").processed)生成的URL链接,您会发现它会将您重定向到Amazon S3上托管的图像。

© www.soinside.com 2019 - 2024. All rights reserved.