・ Ruby: 2.5.7 Rails: 5.2.4 ・ Vagrant: 2.2.7 -VirtualBox: 6.1 ・ OS: macOS Catalina
You have already registered an AWS account.
The following has been implemented.
・ Implementation of posting function -Implementation of image posting function using Carrierwave
AWS Management Console (https://ap-northeast-1.console.aws.amazon.com/console/home?region=ap-northeast-1)
Service
User
Add User
** ① Enter your user name. (Appropriate) **
** ② Set the access type to programmatic access
. ** **
** ③ Click Next Step: Access Restriction
**
Attach existing policy directly
and click
Next Step: Tag`Next Step: Confirm
Create User
access key ID
and secret access key
, make a note of them, and click service
.S3
Create Bucket
** ① Enter the bucket name. (Appropriate) **
** ② Set the region to Asia Pacific (Tokyo)
. ** **
** ③ Click Next
. ** **
Next
Next
Create Bucket
** ① Introduced "gem'dotenv-rails'" **
Gemfile
gem 'dotenv-rails'
Terminal
& bundle
** ② Create a ".env" file directly under the application **
Terminal
$ touch .env
** ③ Edit the .env
file **
.env
S3_ACCESS_KEY_ID = 'access key' #Postscript
S3_SECRET_ACCESS_KEY = 'Secret access key' #Postscript
** ④ Edit the .gitignore
file **
.gitignore
/.env #Postscript
Gemfile
gem 'fog-aws'
Terminal
$ bundle
Comment out storage: file
on the 7th line and add the following code.
image_uploader.rb
#Postscript
if Rails.env.development? #For development environment
storage :file
elsif Rails.env.test? #For test environment
storage :file
else #For production environment
storage :fog
end
storage :file
➡︎ Upload the image into the application.
storage :fog
➡︎ Upload the image to S3.
carrierwave.rb
Terminal
$ touch config/initializers/carrierwave.rb
carrierwave.rb
require 'carrierwave/storage/abstract'
require 'carrierwave/storage/file'
require 'carrierwave/storage/fog'
CarrierWave.configure do |config|
if Rails.env.production? #Upload to S3 in production environment
config.storage :fog
config.fog_provider = 'fog/aws'
config.fog_directory = 'matsubishi-sample' #Bucket name
config.fog_public = false
config.fog_credentials = {
provider: 'AWS',
aws_access_key_id: ENV['S3_ACCESS_KEY_ID'], #access key
aws_secret_access_key: ENV['S3_SECRET_ACCESS_KEY'], #Secret access key
region: 'ap-northeast-1', #region
path_style: true
}
else #Upload within the application if not in production
config.storage :file
config.enable_processing = false if Rails.env.test?
end
end
Recommended Posts