【问题标题】:Rails Active Storage: Direct upload from modelRails Active Storage:从模型直接上传
【发布时间】:2020-02-01 16:48:33
【问题描述】:

我正在为我的网站创建站点地图,我需要将其上传到 S3,因为 Heroku 临时文件系统。

我已经使用 Amazon S3 配置了 Active Storage,但我不想仅为单个上传创建模型实体。有没有办法:

sitemap.rb

  1. 使用 Active Storage 将生成的文件“public/sitemaps/sitemap.xml.gz”上传到 S3
  2. 检索网址

【问题讨论】:

    标签: ruby-on-rails rails-activestorage


    【解决方案1】:

    错误的工具。

    Active Storage 有助于将文件上传到云存储服务 像 Amazon S3、Google Cloud Storage 或 Microsoft Azure Storage 和 将这些文件附加到 Active Record 对象。

    ActiveStorage 是围绕将文件附加到模型而构建的。尝试在没有模型的情况下使用它会非常痛苦,因为您要针对 ActiveStorage 的整个设计。

    如果您只想上传在服务器上创建的文件,请改用aws-sdk-ruby gem

    require 'aws-sdk-s3'
    
    s3 = Aws::S3::Resource.new(region:'us-west-2')
    obj = s3.bucket('bucket-name').object('key')
    obj.upload_file('/path/to/source/file', { acl: 'public-read' })
    # Returns Public URL to the file
    obj.public_url
    

    upload an Object Using the AWS SDK for Ruby

    【讨论】:

    • 好的,有道理。如何创建“公共 url”,以便 google 等外部资源可以访问它而不会过期?
    • 如果不确定您的意思,该示例会将公共 url 返回到在 S3 上创建的资源。如果你想在你的 Rails 应用程序中有一个固定的 URL 来提供资源,你可以创建一个重定向或代理的控制器。
    • 我试图访问生成的 url,但它显示“AccessDenied”。 URL:my-bucket.s3.amazonaws.com/key 文件已正确上传到文件 S3 桶中
    • 啊,你得设置ACL。 obj.upload_file('/path/to/source/file', { acl: 'public-read' })docs.aws.amazon.com/AmazonS3/latest/dev/acl-overview.html
    猜你喜欢
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 2021-04-18
    • 2023-03-13
    • 2019-12-24
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    相关资源
    最近更新 更多