3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails carrierwave fog rmagickで画像アップロード

Last updated at Posted at 2018-04-07

プロダクト開発でアイコンやバックグラウドイメージをアップロードできるようにしたいので試しに使用してみました。
すでに色々な方々が試しているみたいですが、自分なりの備忘として残しておきます。
環境変数はハードコーディングせずにgem:dotenvを使用して実装しています。

carrierwave

config/initializers/carrierwave.rb
CarrierWave.configure do |config|
  config.fog_credentials = {
    provider: 'AWS',
    aws_access_key_id: ENV['AWS_ACCESS_KEY_ID'],
    aws_secret_access_key: ENV['AWS_SECRET_ACCESS_KEY'],
    region: ENV['AWS_REGION'],
    path_style: true
  }
  config.fog_public = true
  config.fog_attributes = {'Cache-Control' => 'public, max-age=86400'}
  config.remove_previously_stored_files_after_update = false
  config.cache_storage = :fog

  case Rails.env
  when 'production'
    config.fog_directory  = ENV['AWS_S3_BUCKET']
  end
end
# 日本語の文字化けを防ぐ
CarrierWave::SanitizedFile.sanitize_regexp = /[^[:word:]\.\-\+]/

Uploader

app/uploaders/image_uploader.rb
class ImageUploader < CarrierWave::Uploader::Base
  include CarrierWave::RMagick

  storage :fog
  def store_dir
    "images/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

  version :thumb do
    process resize_to_fit: [100, 100]
  end

  def extension_whitelist
    %w(jpg jpeg png)
  end

  def filename
    "image_#{model.id}.#{file.extension}" if original_filename
  end
end

Model

class User < ApplicationRecord
  mount_uploader :icon, ImageUploader
end

参考
https://qiita.com/msyk_tym/items/7d1c8e3666c11741d2de
http://morizyun.github.io/blog/carrierwave-image-uploader-rails/
https://github.com/carrierwaveuploader/carrierwave

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?