2015-05-25 81 views
1

我很難讓Carrierwave在裁剪後的版本中刪除原始文件。我爲用戶製作了600像素的上傳版本,但裁剪後我希望該版本被刪除,因爲它從未在網站上使用過。Carrierwave和Jcrop,裁剪後刪除原件?

我嘗試了幾種在線搜索的解決方案,但它們都在刪除作物之前的大版本,而不是之後。

這裏是我的Carrierwave上傳:

# encoding: utf-8 

class AvatarUploader < CarrierWave::Uploader::Base 

    include CarrierWave::RMagick 

    storage :file 
    # storage :fog 

    def store_dir 
    "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}" 
    end 

    # Only allows jpg, jpeg, or png 
    def extension_white_list 
    %w(jpg jpeg png) 
    end 

    resize_to_limit(600, 600) 

    version :profile do 
    process :crop 
    resize_to_fill(120, 120) 
    def full_filename (for_file = model.file) 
     "profile.png" 
    end 
    end 

    version :timeline do 
    process :crop 
    resize_to_fill(50, 50) 
    def full_filename (for_file = model.file) 
     "timeline.png" 
    end 
    end 

    version :navigation do 
    process :crop 
    resize_to_fill(20, 20) 
    def full_filename (for_file = model.file) 
     "navigation.png" 
    end 
    end 

    def crop 
    if model.crop_x.present? 
     resize_to_limit(600, 600) 
     manipulate! do |img| 
     x = model.crop_x.to_i 
     y = model.crop_y.to_i 
     w = model.crop_w.to_i 
     h = model.crop_h.to_i 
     img.crop!(x, y, w, h) 
     end 
    end 
    end 

end 

回答

1

您既可以使用一個after_store回調(使用File.delete),以刪除原始文件,或使您需要的最大尺寸,你可以修改原始:

version :normal do 
    process :resize_to_limit => [600,600] 
end 
+0

after_store在這種情況下似乎不起作用,因爲裁剪不會在上傳時發生。因此,大文件被存儲,然後刪除,然後我可以使用jCrop編輯它。 –

+0

@RichCoy你可以將刪除邏輯移動到保存編輯圖像的'after_save'回調中 –

+0

對不起,我有點困惑。那會進入上傳器還是控制器? –

0

對於那些試圖解決問題的情況下添加一些修訂信息的圖像名稱(例如裁剪),我找到了一種方法來做到這一點。

# :large is the cropped version 
version :small_square, from_version: :large do 
    before :cache, :reset_revision 
    after :store, :remove_old_revision 

    def full_filename(for_file) 
    fname = super(for_file) 
    "#{ fname.pathmap('%n') }_#{ model.image_revision }#{ fname.pathmap('%x') }" 
    end 

    def full_original_filename 
    "#{ super.pathmap('%n') }_#{ model.image_revision }#{ super.pathmap('%x') }" 
    end 

    def remove_old_revision(file = nil) 
    File.delete(@old_path) if @old_path && File.exists?(@old_path) 
    end 

    def reset_revision(file = nil) 
    # Otherwise we'll get `cannot update new record` error 
    if model.persisted? 
     # Creating an instance variable that will be used after storing the cropped version 
     @old_path = File.join(Rails.public_path, model.public_send(mounted_as).store_dir, full_original_filename) 

     # I use :image_revision column in the DB 
     model.update_columns(image_revision: SecureRandom::hex(8)) 
    else 
     model.image_revision = SecureRandom::hex(8) 
    end 
    end 

    process :crop_small_square 
end 

所以,它的存儲改變所產生的圖像名稱,然後刪除第一個版本之前的修剪版本的第一個版本的路徑。

花了我一些時間來弄清楚如何將一些abracadabra附加到文件的明確版本的末尾:它採用更新操作,而不是僅指定屬性。 Carrierwave的文檔並不準確。