2017-07-05 104 views
0

我使用帶有霧的CarrierWave將我的圖片上傳到S3。與carrierwave相同型號的動態商店陳列櫃

我有模型圖像,可以表示不同大小的圖像,並根據需要保存在不同的文件夾。

例如,對於image.jpg我可以有一個需要兩個不同的版本上傳來保存爲:

'images/large/image.jpg' 
'images/small/image.jpg' 

有可能使用minimagick不能涵蓋所有這些是用例和版本任意數量。

到目前爲止我還沒有找到解決方案。有誰知道如何做到這一點?

回答

0

我已經看到了這個問題問了幾次,所以我會寫什麼我的最終解決方案是。

我沒有在模型上定義mount_uploader,而是決定單獨使用上傳器並將URL保存到記錄中。

動態變化store_dir和文件名可以這樣

uploader = Uploader.new 

uploader.define_singleton_method(:store_dir) do 
    'new_store_dir' 
end 
uploader.define_singleton_method(:filename) do 
    'new_filename' 
end 

uploader.store!(image) 

完成使用這種方法,你也可以定義與局部變量或任何你在控制器可用名稱。

希望它可以幫助別人。

0

爲了改變那裏上傳的文件放在,只是重寫store_dir方法:,對於你的情況(reference link

class Image < CarrierWave::Uploader::Base 
storage :file 
    # this if you using use condition for folder location 
    def store_dir 
    if model.somefield == "somecondition 
     "uploads/#{model.somefield}" 
    elsif model.somefield == "somecondition 
     "uploads/location2" 
    else 
     "uploads/default_dir" 
    end 

    end 
    # this is if you want to use version_name 
    def store_dir 
    'images/#{version_name}/' 
    end 
end 
+0

我需要能夠爲每個圖像提供不同的目錄,以便version_name不起作用。我需要3-4個不同的商店目錄,並根據使用的文件字段來選擇保存哪一個目錄,這可能嗎? – IvanV

+0

你可以使用邏輯,如果在store_dir裏面,我只是編輯我的答案 – widjajayd