【问题标题】:Migrate active storage from local disk service to gcs cloud将活动存储从本地磁盘服务迁移到 gcs 云
【发布时间】:2019-08-03 11:04:39
【问题描述】:

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

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

我的本​​地存储目录具有完全不同的文件夹结构,其中的文件夹如下: /storage/1R/3o/NWuT....

我获取图片的方法如下:

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

我在这里错过了什么?

【问题讨论】:

    标签: ruby-on-rails rails-activestorage


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 2021-01-04
      • 2022-10-13
      • 2019-04-12
      • 1970-01-01
      • 1970-01-01
      • 2013-05-07
      • 2019-02-11
      • 2013-06-02
      • 2020-06-16
      相关资源
      最近更新 更多