将活动存储从本地磁盘服务迁移到 gcs 云

Migrate active storage from local disk service to gcs cloud

我正在尝试将我的本地 Active Storage 文件迁移到 Google Cloud Storage。我试图将 /storage/* 的文件复制到我的 GCS Bucket - 但似乎这不起作用。

我收到 404 not found 错误,因为它正在搜索如下文件: [bucket]/variants/ptGtmNWuTE...

我的本地存储目录有一个完全不同的文件夹结构,例如: /storage/1R/3o/NWuT....

我取回图片的方法如下:

variant = attachment.variant(resize: '100x100').processed
url_for(variant)

我在这里错过了什么?

事实证明 - 又名 DiskService。本地存储使用与云服务不同的文件夹结构。真是奇怪。

DiskService 将密钥的第一个字符用作文件夹部分。 云服务只使用密钥并将所有变体放在单独的文件夹中。

创建了一个 rake 任务来将文件复制到云服务。 运行 以 rails active_storage:migrate_local_to_cloud storage_config=google 为例。

namespace :active_storage do
  desc "Migrates active storage local files to cloud"
    task migrate_local_to_cloud: :environment do
      raise 'Missing storage_config param' if !ENV.has_key?('storage_config')

      require 'yaml'
      require 'erb'
      require 'google/cloud/storage'

      config_file = Pathname.new(Rails.root.join('config/storage.yml'))
      configs = YAML.load(ERB.new(config_file.read).result) || {}
      config = configs[ENV['storage_config']]

      client = Google::Cloud.storage(config['project'], config['credentials'])
      bucket = client.bucket(config.fetch('bucket'))

      ActiveStorage::Blob.find_each do |blob|
        key = blob.key
        folder = [key[0..1], key[2..3]].join('/')
        file_path = Rails.root.join('storage', folder.to_s, key)
        file = File.open(file_path, 'rb')
        md5 = Digest::MD5.base64digest(file.read)
        bucket.create_file(file, key, content_type: blob.content_type, md5: md5)
        file.close
        puts key
      end
    end
  end