14

使用标准 S3 配置:

AWS_ACCESS_KEY_ID:        [AWS ID]
AWS_BUCKET:               [bucket name]
AWS_REGION:               [region]
AWS_SECRET_ACCESS_KEY:    [secret]

我可以使用此 Rails 5.2 代码(仅显示相关代码)将文件上传到 S3(使用直接上传):

form.file_field :my_asset, direct_upload: true

提交表单后,这将有效地将我的资产放在我的 S3 存储桶的根目录中。

如何指定前缀(例如“development/”,以便我可以模仿 S3 上的文件夹)?

4

6 回答 6

11

我目前在 S3 上的解决方法(至少在 ActiveStorage 引入为has_one_attachedhas_many_attached宏传递路径的选项之前)是实现move_to 方法

所以我让 ActiveStorage 像现在通常那样(在存储桶的顶部)将图像保存到 S3,然后将文件移动到文件夹结构中。

move_to方法基本上将文件复制到您传递的文件夹结构中,然后删除放在存储桶根目录的文件。这样,您的文件就会到达您想要的位置。

因此,例如,如果我们要存储驱动程序详细信息:namedrivers_license,请将它们保存为您已经在执行的操作,以便它位于存储桶的顶部。

然后执行以下操作(我把我的放在一个助手中):

        module DriversHelper

          def restructure_attachment(driver_object, new_structure)

          old_key = driver_object.image.key

          begin
            # Passing S3 Configs
            config = YAML.load_file(Rails.root.join('config', 'storage.yml'))

            s3 = Aws::S3::Resource.new(region: config['amazon']['region'],
                                       credentials: Aws::Credentials.new(config['amazon']['access_key_id'], config['amazon']['secret_access_key']))

            # Fetching the licence's Aws::S3::Object
            old_obj = s3.bucket(config['amazon']['bucket']).object(old_key)

            # Moving the license into the new folder structure
            old_obj.move_to(bucket: config['amazon']['bucket'], key: "#{new_structure}")


            update_blob_key(driver_object, new_structure)
          rescue => ex
            driver_helper_logger.error("Error restructuring license belonging to driver with id #{driver_object.id}: #{ex.full_message}")
          end
          end

          private

          # The new structure becomes the new ActiveStorage Blob key
          def update_blob_key(driver_object, new_key)
            blob = driver_object.image_attachment.blob
            begin
              blob.key = new_key
              blob.save!
            rescue => ex
              driver_helper_logger.error("Error reassigning the new key to the blob object of the driver with id #{driver_object.id}: #{ex.full_message}")
            end
          end

          def driver_helper_logger
            @driver_helper_logger ||= Logger.new("#{Rails.root}/log/driver_helper.log")
          end
        end

更新 blob 键很重要,这样对键的引用就不会返回错误。

如果密钥没有更新,任何试图引用图像的函数都会在它以前的位置(在存储桶的顶部)而不是在它的新位置中查找它。

一旦文件被保存(即在创建操作中),我就会从我的控制器调用这个函数,这样即使不是,它看起来也是无缝的。

虽然这可能不是最好的方法,但它现在有效。

仅供参考:根据您给出的示例,new_structure变量将是new_structure = "development/#{driver_object.image.key}".

我希望这有帮助!:)

于 2018-05-22T15:17:19.433 回答
4

谢谢你,索尼娅,你的回答。

我尝试了您的解决方案,效果很好,但我遇到了覆盖附件的问题。我在做的时候经常遇到IntegrityError 。我认为,这和校验和处理可能是 Rails 核心团队不想添加传递路径名功能的原因。这将需要更改上传方法的整个逻辑。

ActiveStorage::Attached#create_from_blob方法,也可以接受一个ActiveStorage::Blob对象。所以我尝试了一种不同的方法:

  1. 使用代表所需文件结构和上传附件的键手动创建Blob 。
  2. 使用 ActiveStorage 方法附加创建的Blob 。

在我的使用中,解决方案是这样的:

def attach file # method for attaching in the model
  blob_key = destination_pathname(file)
  blob = ActiveStorage::Blob.find_by(key: blob_key.to_s)

  unless blob
    blob = ActiveStorage::Blob.new.tap do |blob|
      blob.filename = blob_key.basename.to_s
      blob.key = blob_key
      blob.upload file
      blob.save!
    end
  end

  # Attach method from ActiveStorage
  self.file.attach blob
end

由于将完整路径名传递给Blob的密钥,我在服务器上收到了所需的文件结构。

于 2018-09-05T09:16:33.203 回答
4

2022 年更新:从 Rails 6.1 开始(检查此提交),这实际上是受支持的:

user.avatar.attach(key: "avatars/#{user.id}.jpg", io: io, content_type: "image/jpeg", filename: "avatar.jpg")
于 2022-01-26T18:32:59.380 回答
2

抱歉,目前无法实现。我建议创建一个供 Active Storage 独占使用的存储桶。

于 2018-01-23T02:15:05.807 回答
0

上面的解决方案还是会报IntegrityError,需要使用 File.open(file)。谢谢你的想法。

class History < ApplicationRecord
  has_one_attached :gs_history_file

  def attach(file) # method for attaching in the model
    blob_key = destination_pathname(file)
    blob = ActiveStorage::Blob.find_by(key: blob_key.to_s)
    unless blob
      blob = ActiveStorage::Blob.new.tap do |blob|
        blob.filename = blob_key.to_s
        blob.key = blob_key
        #blob.byte_size = 123123
        #blob.checksum = Time.new.strftime("%Y%m%d-") + Faker::Alphanumeric.alpha(6)
        blob.upload File.open(file)
        blob.save!
      end
    end

    # Attach method from ActiveStorage
    self.gs_history_file.attach blob
  end

  def destination_pathname(file)
    "testing/filename-#{Time.now}.xlsx"
  end
end
于 2020-06-23T04:50:43.767 回答
0

2022年的解决方案是什么?我想将我的文件存储在

 my-bucket/some-folder/myfile.somefile

使用 Active Storage 很好地做到这一点似乎仍然是不可能的。

于 2022-02-09T23:42:33.197 回答