【问题标题】:How to get Object URL(link) from AWS S3 using rails (API JSON Response)如何使用 Rails(API JSON 响应)从 AWS S3 获取对象 URL(链接)
【发布时间】:2021-04-23 19:33:43
【问题描述】:

我有一个应用程序,我可以在其中从管理仪表板上传图像和视频,这一切都运行良好,我唯一不能做的就是我如何(有可能)获取对象 url 并响应它作为json,

目前我收到此回复:

{

images: [
"https://promoteur-api.s3.eu-west-3.amazonaws.com//rails/active_storage/blobs/redirect/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBNQT09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--f4fdd1c0fd4b07b03b0282a63c8fa1ca31d310c6/41567.png",
]
}

我希望它是这样的:

{

images: [
"https://promoteur-api.s3.eu-west-3.amazonaws.com/AWS_OBJECT_ID",
]
}

这是我的#serializer.rb

class ProjetSerializer < ActiveModel::Serializer
  include Rails.application.routes.url_helpers
  attributes :id, :nom, :gouvernorat, :localite, :surface, :description, :en_cours, :fini,  :images
  
  def images
    object.images.map do |image|
      Rails.application.routes.url_helpers.rails_blob_url(image, only_path: true) if object.images.attached?
    end
  end

end

我需要直接访问图像 URL 以在我的颤振应用程序中显示它们,如果你有更简单的方法来代替这个,请告诉我,

提前致谢。

【问题讨论】:

    标签: ruby-on-rails json ruby api amazon-s3


    【解决方案1】:

    对象服务URL可以使用service_url方法

    新的串行器

    class ProjetSerializer < ActiveModel::Serializer
      attributes :id, :nom, :gouvernorat, :localite, :surface, :description, :en_cours, :fini,  :images
      
      def images
        object.images.map do |image|
          image.service_url if object.images.attached?
        end
      end
    end
    

    但是这个网址会在一段时间后过期

    如果你想改变过期时间

    # config/initializers/active_storage.rb
    Rails.application.config.active_storage.service_urls_expire_in = 1.hour
    

    【讨论】:

    • 谢谢@Kemal_AKIN,我尝试了image.service_url,但它给了我一个零错误bad URI(is not URI?): nil我记得我之前尝试过这个,但无法修复这个错误:/
    • 我认为你是在本地开发环境中使用磁盘服务你能不能这样描述一下并尝试ActiveStorage::Current.host = 'http://localhost:3000'
    • 这就是问题所在,我将我的活动存储从本地切换到亚马逊,它完成了工作,我现在要在生产中检查它config.active_storage.service = :amazon
    【解决方案2】:

    看起来你的代码是正确的,也许你没有在你的 env 文件中设置主机 url?如果没有,请在development.rb 中添加Rails.application.routes.default_url_options[:host] = 'this_is_base_url.com'

    【讨论】:

    • 谢谢@TTD,我在我的application_controller 中设置了这是我正在使用class ApplicationController &lt; ActionController::Base Rails.application.routes.default_url_options[:host] = 'https://promoteur-api.s3.eu-west-3.amazonaws.com' end 的行,我得到了所需网址的前半部分,我需要做的就是以某种方式从 s3 存储中检索 ObjectID,使其像这样https://promoteur-api.s3.eu-west-3.amazonaws.com/5vf79jb3xb0qqkdhsh6jww4irpls
    • 尝试用service_url替换rails_blob_url
    • 给我这个错误bad URI(is not URI?): nil
    猜你喜欢
    • 2017-10-24
    • 2019-06-09
    • 2020-01-19
    • 2020-01-18
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    相关资源
    最近更新 更多