如何在上传到 S3 之前临时存储(缓存)图像?

How can I temporarily store (cache) images before uploading to S3?

提问人:Ozge Cokyasar 提问时间:1/14/2019 更新时间:10/5/2020 访问量:1268

问:

我的 rails 应用程序正在使用 CarrierWave 和 Fog 将图像上传到 S3。远程 URL 工作正常,但是我需要暂时存储本地图像(从正在上传的设备),然后才能将这些本地图像上传到 S3。我该怎么做?

如何缓存我的图像?

愿景表:

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

      t.timestamps
    end
  end
end

视觉模型:

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
Ruby-on-Rails Amazon-S3 Ruby-on-Rails-5 载波

评论


答:

0赞 H Dox 1/14/2019 #1

根据文档,有一个名为的选项,可让您在上传之前定义用于存储临时文件的目录。cache_dir

看看这个链接:

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

评论

0赞 Ozge Cokyasar 1/17/2019
谢谢。我添加了 ''' def cache_dir '/tmp/projectname-cache' end ''' 但它似乎没有保存或创建目录。当使用以下参数发出请求时: 我得到以下信息:Parameters: {"vision"=>{"description"=>"YOYOY", "image"=>"file:///Users/ozgecokyasar/L3A30BAE7BA6D/data/Containers/Data/Application/6F633096-E665-46BB-952F-2775DD85A4A6/Library/Caches/ExponentExperienceData/%.jpg"}}ActiveRecord::RecordInvalid (Validation failed: Image trying to download a file which is not served over HTTP):
2赞 Elena Unanyan 10/5/2020 #2

您应该添加以下内容:

 config.storage         = :fog
 config.cache_storage   = :file