Upload images posted in Active_Storage to AWS S3 and view images retrieved from AWS S3

Asked 2 years ago, Updated 2 years ago, 88 views

Implemented the ability to upload photos using Active_Storage.
After deployment, when I post photos, I use S3 to save them to the database and try to retrieve them from .

The object URL of the image uploaded from the development environment to S3 is "https://<bucket name>.s3-ap-northeast-1.amazonaws.com/< key>" and cannot be read in the production environment. (By the way, there is an error uploading the image in the production environment.)
Even if you specify url_for(hoge.hoge) in the Rails View file, the addresses displayed in the validation indicate different addresses.

Therefore, in application.rb, I try to display and post images by specifying "config.active_storage.routes_prefix='https://<bucket name>.s3-ap-northeast-1.amazonaws.com/'", but I cannot specify the above key.

Production.rb

config.active_storage.service=:amazon

storage.yml

amazon:
  service —S3
  access_key_id:<%=Rails.application.credentials.dig(:aws,:access_key_id)%>
  secret_access_key:<%=Rails.application.credentials.dig(:aws,:secret_access_key)%>
  region —ap-northeast-1
  bucket —The bucket name.

credentials:edit

aws:
  access_key_id:id
  secret_access_key —Access key

The policy is also configured.
In the development environment, I can upload with the above code, so I think there are no errors in the description.

If anyone knows anything, please let me know.

ruby-on-rails aws amazon-s3

2022-09-29 21:20

1 Answers

I was able to solve myself.

Changes

Views

<%=f.file_field:thumbnail,direct_upload:true,accept:"thumbnail/png,thumbnail/jpeg,thumbnail/gif,thumbnail/jpg"%> 

Add to Bucket Policy

"Resource":["arn:aws:s3::bucketname", "arn:aws:s3::bucketname/*" ]

Run aws configure on the EC2 instance and enter the region directly


2022-09-29 21:20

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.