如何在上传到S3之前临时存储(缓存)图像? [英] How can I temporarily store (cache) images before uploading to S3?

查看:220
本文介绍了如何在上传到S3之前临时存储(缓存)图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Rails应用程序正在使用CarrierWave和Fog将图像上传到S3.远程URL可以正常工作,但是在将本地图像上传到S3之前,我需要临时存储本地图像(从正在上传的设备上).我该怎么办?

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?

如何缓存图像?

视野表:

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

推荐答案

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

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

看看这个链接:

https://github.com/carrierwaveuploader/carrierwave#changing-the -存储目录

这篇关于如何在上传到S3之前临时存储(缓存)图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆