簡體   English   中英

如何使用 rake 任務將圖像保存在 Google 存儲桶中

[英]How to save images in Google storage bucket with a rake task

我有一個使用 Active Storage 的 Rails 應用程序,其中一些任務應該每天運行以將圖像附加到 model 並將它們存儲在 Google Cloud 的存儲桶中。

當我運行任務“ rake attach_image:attach_image_to_cloud ”來附加圖像時,它顯示:

Google::Cloud::PermissionDeniedError: forbidden: attach-images-app@attach-images.iam.gserviceaccount.com does not have storage.buckets.get access to the Google Cloud Storage bucket.

Caused by:
Google::Apis::ClientError: forbidden: attach-images-app@attach-images.iam.gserviceaccount.com does not have storage.buckets.get access to the Google Cloud Storage bucket.

我按照“ 使用 Google 雲存儲和 Heroku 設置 Rails 5.2 Active Storage ”並認為我做的一切都是對的。

我的 Ruby 版本是 2.5.3,Rails 是 5.2.2。

我的任務是:

def download_data(download_url, datetime, json_data)
  puts "Downloading fields"
  @field = Field.new(datetime: datetime, json_data: json)
  puts "Saving field, datetime: #{datetime}"
  attach_image(download_url, datetime, @field)
  @field.save
  puts "Finished downloading #{datetime} field"
end

def attach_image(download_url, datetime, field)
  link = download_url
  field.image.attach(io: open(link), filename: "global_#{datetime}.png")
end

download_data(download_url, some_datetime, json_data)

這是我的 model field.rb:

class Field < ApplicationRecord
  has_one_attached :image
end

這是我的 config.yml:

google:
  service: GCS
  project: attach-images
  credentials: <%= ENV['GOOGLE_APPLICATION_CREDENTIALS'].as_json %>
  bucket: fields
google_dev:
  service: GCS
  project: attach-images
  credentials: <%= Rails.root.join("config/secrets/attach_images.json") %>
  bucket: fields

這些在我的 development.rb 和 production.rb 環境文件中:

config.active_storage.service = :google_dev

config.active_storage.service = :google

我運行了bundle install

gem "google-cloud-storage", "~> 1.8", require: false

我的存儲桶和我的服務帳戶密鑰都已正確創建並且憑據具有所有者規則。 憑據是在 Google Cloud 的控制台中創建時下載的 hash,並在我的開發和 Heroku 生產環境中正確設置。

我找到了解決這個問題的方法。 通過使用 gsutil cors 命令在存儲桶上配置 CORS 解決了該問題。

gsutil cors set [JSON_FILE_NAME].json gs://[BUCKET_NAME]

而 json 文件的內容是:

[
  {
    "origin": ["*"],
    "responseHeader": ["Content-Type", "Content-Md5", "Origin", "X-Requested-With", "Accept", "Authorization"],
    "method": ["PUT", "GET", "HEAD", "DELETE", "OPTIONS"],
    "maxAgeSeconds": 3600
  }
]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM