简体   繁体   中英

Google Cloud Storage - getting public URL without knowing specific filename

I have a Rails 5.2.3 app being hosted on Google Cloud services. On my frontend, I require users to upload images of their employees, and these images get saved into a GC Storage bucket, and importantly for my question, they're saved with randomized names . There's hundreds of these images, and they all have what basically amounts to random 40+ character strings as names inside the buckets.

In the DB, each User has multiple Employees, and each Employee has one image attached.

I'm trying to create an Email in which I need to include an image of one specific employee for each user. Right now, I'm using the ActiveStorage::service_url method, but the problem is that the service_url method will return a Signed URL from GCS, which has a (by default) 5 minute TTL, meaning the image will stop being accessible after 5 minutes and users get a broken image. The image does actually show up fine initially, it just expires after 5 minutes.

An example of how I'm using the service_url method in my mailer view

<%= image_tag (employee.photo.service_url) if employee.photo.attached? %>

Now, the GCS docs state that to get the public URL, you just have to use the BUCKET_NAME/FILE_NAME URL, but because there's hundreds of these files and they're saved with randomized names (I'm not the one that set that up initially, don't ask why), I simply don't have a way of doing that in a sensible way for each user, especially since this is a weekly email that goes out to each and every user denoting their staff members that are performing the best, so even for one client the email will use a different picture from week to week.

Is there any way for me to get the public image URL for use in these emails?

My storage.yml file

google:
  service: GCS
  project: REDACTED
  credentials: <%= Rails.application.credentials.gcs_storage_credentials.to_json %>
  bucket: images-REDACTED

My production.rb env file

config.active_storage.service = :google
config.action_mailer.asset_host = Rails.application.credentials.send(production_server_url)

My Gemfile

ruby '2.6.3'
gem 'rails', '~> 5.2.3'
gem 'pg', '>= 0.18', '< 2.0'
gem 'active_storage_base64'
gem 'google-cloud-storage', '~> 1.8', require: false

You can set the expiry per URL :

image_tag(employee.photo.service_url(expires_in: 1.year.to_i))

While max's answer is a good one should you have a need for your assets eventually expiring, I needed a more permanent solution. Turns out it was really simple, I simple had to call employee.photo and GCS seems to be spitting out a permanent URL!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM