Wednesday, April 24, 2024
HomeRuby On RailsFile Uploads and Cloud Storage

File Uploads and Cloud Storage


# Terminal
bundle add aws-sdk-s3
rails g scaffold photos title
rails active_storage:set up
yarn add @rails/activestorage
# app/javascript/utility.js
import * as ActiveStorage from "@rails/activestorage"
ActiveStorage.begin()
# fashions/image.rb
class Image < ApplicationRecord
  has_one_attached :picture
finish
# views/photos/_form.html.erb
<div class="mb-3">
  <%= kind.label :picture, class: 'form-label' %>
  <%= kind.file_field :picture, class: 'form-control', direct_upload: true %>
</div>
# views/photos/_picture.html.erb
<%= image_tag url_for(image.picture) if image.picture.hooked up? %>
# pictures_controller.rb
def picture_params
  params.require(:image).allow(:title, :picture)
finish
# config/environments/manufacturing.rb
config.active_storage.service = :cloud
# config/storage.yml
# Wasabi
# cloud:
#   service: S3
#   endpoint: https://s3.wasabisys.com
#   access_key_id: <%= ENV['ACCESS_KEY_ID'] %>
#   secret_access_key: <%= ENV['SECRET_ACCESS_KEY'] %>
#   area: <%= ENV['REGION_NAME'] %>
#   bucket: <%= ENV['BUCKET_NAME'] %>

# Backblaze B2
# cloud:
#   service: S3
#   endpoint: https://YOURBUCKETNAME.s3.us-west-000.backblazeb2.com
#   access_key_id: <%= ENV['ACCESS_KEY_ID'] %>
#   secret_access_key: <%= ENV['SECRET_ACCESS_KEY'] %>
#   area: <%= ENV['REGION_NAME'] %>
#   bucket: <%= ENV['BUCKET_NAME'] %>
#   force_path_style: true

# Cloudflare R2
cloud:
  service: S3
  endpoint: https://YOURACCOUNTID.r2.cloudflarestorage.com/instance
  access_key_id: <%= ENV['ACCESS_KEY_ID'] %>
  secret_access_key: <%= ENV['SECRET_ACCESS_KEY'] %>
  area: auto
  bucket: <%= ENV['BUCKET_NAME'] %>
# Backblaze B2 CLI software
https://www.backblaze.com/b2/docs/quick_command_line.html

chmod +x b2-darwin
./b2-darwin authorize-account
./b2-darwin update-bucket --corsRules '[
    {
        "corsRuleName": "downloadFromAnyOriginWithUpload",
        "allowedOrigins": [
            "*"
        ],
        "allowedHeaders": [
            "*"
        ],
        "allowedOperations": [
            "s3_put"
        ],
        "maxAgeSeconds": 3600
    }
]' exampledr allPublic
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments