How can I temporarily store (cache) images before

2019-08-24 05:27发布

问题:

My rails app is using CarrierWave and Fog to upload images to S3. Remote URLs are working fine, HOWEVER I need to temporarily store local images (from the device it's being uploaded) before I can upload these local images to S3. How do I go about this?

How do I cache my images?

Vision table:

class CreateVisions < ActiveRecord::Migration[5.1]
  def change
    create_table :visions do |t|
      t.string :image
      t.text :description

      t.timestamps
    end
  end
end

Vision model:

class Vision < ApplicationRecord
    belongs_to :user
    mount_uploader :image, ImageUploader

end

Visions_controller.rb:

  def create
    @vision = current_user&.visions.build(vision_params)
    @vision.save!
    render :create, status: :created
  end

Image_uploader.rb:

class ImageUploader < CarrierWave::Uploader::Base

  # Include RMagick or MiniMagick support:
  # include CarrierWave::RMagick
  include CarrierWave::MiniMagick
  # Choose what kind of storage to use for this uploader:
  if Rails.env.production?
    storage :fog
  else
    storage :file
  end

  # Override the directory where uploaded files will be stored.
  # This is a sensible default for uploaders that are meant to be mounted:
  def store_dir
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
  end

setup_fog.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_ID'] || '',  
      region: 'us-west-2'
    }

    config.fog_directory = 'pranaapp' # AWS S3 Bucket Name
    config.fog_public = false
    config.fog_attributes = {
      'Cache-Control' => "max-age=#{365.day.to_i}"
    }
  end

回答1:

According to the docs, there is an option named cache_dir that let you define the directory for storing temp file before uploading.

Take a look at this link:

https://github.com/carrierwaveuploader/carrierwave#changing-the-storage-directory