所以我有一个网站已经在生产中使用了carrierwave gem,图像存储在amazon s3上。我的上传器使用store_dir
方法指定要放入已处理图像的特定结构。
好吧,现在在我的开发环境中,我添加了carrierwave_direct gem,开始直接上传到S3。问题是这个gem完全覆盖了我的上传器中的store_dir和filename默认值。我无法推动我的完全工作上传者,因为我的所有旧图像链接都将被破坏。
我的理解是CWdirect gem会将原始图像文件上传到S3上的“temp”目录,然后S3会响应并为您提供一个key
变量,这样您就可以抓住这个文件并按照您的看到进行处理适合。那么,我应该在carrierwave中使用一个完全独立的图像上传器类来处理图像并将它们放在正确的文件夹中吗?这意味着我将有一个专用于carrierwave_direct的上传器上传到这个宝石似乎要上传的地方;我将使用链接到我的真实模型的另一个uploader.rb类来保存我当前的store_dir和文件名结构?
在任何情况下,我的基本问题是,如果我已经在生产中使用特定文件夹结构中的图像运行CW,我该如何使用CarrierWave_Direct gem?
答案 0 :(得分:5)
好的,所以我确实知道如何做到这一点,我将在下面解释。我的预感是正确的,使用两个不同的CarrierWave上传器类 - 一个专门用于上传到S3(使用CarrierWave_Direct gem),另一个专门用于图像处理(我已经在生产中使用的类)。我会尝试在下面发布相关代码,但如果有人有问题请告诉我。我不确定为什么我没有看到其他人使用这样的单独的类,但它似乎对我有用。
我的图片上传器类app\uploaders\image_uploader.rb
使用了carrierwave_direct gem:
class ImageUploader < CarrierWave::Uploader::Base
include CarrierWaveDirect::Uploader
include ActiveModel::Conversion
extend ActiveModel::Naming
include CarrierWave::MimeTypes
process :set_content_type
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
def extension_white_list
%w(jpg jpeg gif png)
end
# Include the Sprockets helpers for Rails 3.1+ asset pipeline compatibility:
include Sprockets::Helpers::RailsHelper
include Sprockets::Helpers::IsolatedHelper
# Override the directory where uploaded files will be stored.
# CarrierWaveDirect::Uploader puts raw uploaded files in this directory on S3 as a first step
def store_dir
"unprocessed_uploads"
end
end
**注意在这个课程中没有进行任何处理
我的图像处理类app\uploaders\image_processor.rb
(生产中已经存在的内容):
class ImageProcessor < CarrierWave::Uploader::Base
# Include RMagick or MiniMagick support:
# include CarrierWave::RMagick
include CarrierWave::MiniMagick
include CarrierWave::MimeTypes
process :set_content_type
# Include the Sprockets helpers for Rails 3.1+ asset pipeline compatibility:
include Sprockets::Helpers::RailsHelper
include Sprockets::Helpers::IsolatedHelper
# Choose what kind of storage to use for this uploader:
storage :fog
# 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}"
# "uploads/#{model.class.to_s.underscore}/path/#{model.id}"
end
# Provide a default URL as a default if there hasn't been a file uploaded:
def default_url
"logos/" + [version_name, "default.png"].compact.join('_')
end
# Process files fetched from S3 after they are uploaded:
def make_thumbnail(width, height)
# uses MiniMagick classes to get a square, centered thumbnail image
manipulate! do |img|
if img[:width] < img[:height]
remove = ((img[:height] - img[:width])/2).round
img.shave("0x#{remove}")
elsif img[:width] > img[:height]
remove = ((img[:width] - img[:height])/2).round
img.shave("#{remove}x0")
end
img.resize("#{width}x#{height}")
img
end
end
# Create different versions of your uploaded files:
# the process statement below isn't defined within a version block on purpose--this means the ORIGINAL uploaded photo is constrained to 1050 pics
process :resize_to_limit => [1050, 1050]
process :quality => 85 # this reduces filesize greatly and saves space
version :thumb do
process :make_thumbnail => [100, 100]
process :quality => 85 # this reduces filesize greatly and saves space
end
version :big_thumb do
process :make_thumbnail => [350, 350]
process :quality => 85 # this reduces filesize greatly and saves space
end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
def extension_white_list
%w(jpg jpeg gif png)
end
# Override the filename of the uploaded files:
# Avoid using model.id or version_name here, see uploader/store.rb for details.
def filename
if original_filename
if model && model.read_attribute(:image).present?
model.read_attribute(:image)
else
"#{secure_token}.#{file.extension}"
end
end
end
protected
def secure_token
var = :"@#{mounted_as}_secure_token"
model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.uuid)
end
end
我的照片模型(摘要):
class Photo < ActiveRecord::Base
mount_uploader :image, ImageProcessor
def save_and_process_image(options = {})
s3_unprocessed_image_url = self.image.asset_host + '/' + self.key
# this next line downloads the image from S3
# and this save line below will process the image and reupload to S3 according to ImageProcessor settings
self.remote_image_url = s3_unprocessed_image_url
save
end
end
我也有照片控制器和查看代码可用,如果您想要它让我知道。基本上我使用ImageUploader类来初始上传到S3到一个名为unprocessed_uploads的文件夹。然后S3响应URL中的key
字段,我将其传递给ImageProcessor类 - 这将附加到Photo并处理缩略图和其他图像,然后将它们重新上传到S3上的上传文件夹。
这种分离意味着我在添加carrierwave_direct gem时无需在S3上更改当前的文件夹结构。希望这有助于其他人。如果您需要更多代码,请告诉我,我已经厌倦了打字:)
更新 - 添加更多代码:
照片控制器:
class PhotosController < ApplicationController
def index
@photos = @photos.sort_by(&:created_at)
@uploader = ImageUploader.new
@uploader.success_action_redirect = new_tank_photo_url(@tank)
respond_to do |format|
format.html # index.html.erb
format.json { render json: @photos }
end
end
def create
respond_to do |format|
if @photo.save_and_process_image
format.html { redirect_to tank_photos_path(@tank), notice: 'Photo uploaded successfully and is being processed...' }
format.json { render json: @photo, status: :created, location: @photo }
else
format.html { render :new }
format.json { render json: @photo.errors, status: :unprocessable_entity }
end
end
end
照片索引视图,带有上传按钮的表单:
<%= direct_upload_form_for @uploader, :html => {:class => "form-inline"} do |f| %>
<%= f.file_field :image %>
<%= f.submit "Upload", :class => "btn btn-primary btn-medium" %>
<% end %>
因此,添加了上面的视图/控制器代码,这里是所采取步骤的摘要。请注意ImageUploader
班级与ImageProcessor
班级之间的差异:
希望这有助于解释我的目标