2011-01-20 70 views
14

在我們的最新應用程序中,我們需要處理一些上傳內容,之前我使用過回形針和一切正常工作!但我們給carrierwave一個嘗試,它看起來很有前途,但是,我找不到如何驗證附件的大小,好像documentation沒有關於它的任何信息,我們是否應該手動添加它通過自定義驗證器模型?使用Carrierwave驗證上傳的大小

在此先感謝!

+3

好像他們沒有它(還)只是添加了這個自定義驗證到我的模型,=> https://gist.github.com/795665 – jpemberthy 2011-01-25 21:08:28

+0

我與上述溶液一點工作我。請注意,這隻會驗證圖像​​存儲在緩存中後的大小。在客戶端驗證方面,我仍然在尋找自己 – 2011-03-08 03:07:53

回答

-1

Here is the solution,我想出了 - 的伎倆是,我不能直接檢查文件的大小爲所做的霧RubyGem炸彈,如果該文件早已不是已上傳。如果上傳文件,我希望有一個更清晰的方式來詢問CarrierWave。

5

我製作了一個主動模型File Validators gem,用於檢查Carrierwave,PaperClip,Drangonfly,Refile的內容類型和文件大小驗證(希望它可以與其他上傳解決方案一起使用)。它基於文件的內容檢測內容類型,並且具有媒體類型欺騙檢測器。它可以在上傳之前和之後使用。

-1
taken from https://github.com/carrierwaveuploader/carrierwave/wiki/How-to%3A-Validate-attachment-file-size 

You can use a Rails custom validator to verify your attachment meets specific file size requirements. 

Grab a copy of the validator from https://gist.github.com/1009861 and save it to your lib/ folder as file_size_validator.rb. Add the error translations to config/locales/en.yml or wherever is appropriate for your setup. Then do this in your parent model: 

# app/models/brand.rb 
require 'file_size_validator' 
class Brand < ActiveRecord::Base 
    mount_uploader :logo, BrandLogoUploader 
    validates :logo, 
    :presence => true, 
    :file_size => { 
     :maximum => 0.5.megabytes.to_i 
    } 
end 

Like validates_length_of, validates_file_size accepts :maximum, :minimum, :in [range], and :is options. 

A custom validator could also be used like this. 

# app/models/user.rb 
class User< ActiveRecord::Base 
    attr_accessible :product_upload_limit 
    has_many :products 
end 

# app/models/brand.rb 
class Product < ActiveRecord::Base 
    mount_uploader :file, FileUploader 
    belongs_to :user 
    validate :file_size 

    def file_size 
    if file.file.size.to_f/(1000*1000) > user.product_upload_limit.to_f 
     errors.add(:file, "You cannot upload a file greater than #{upload_limit.to_f}MB") 
    end 
    end 
end 

Here, the upload limit varies from user to user & is saved in the user model. 

other link : 

http://stevenyue.com/2013/04/03/validate-attachment-file-size-and-type-in-rails/ 
https://richonrails.com/articles/getting-started-with-paperclip 
https://gist.github.com/chrisbloom7/1009861 
4

由於1.0版本CarrierWave具有內置的文件大小驗證。

安裝最新carrierwave寶石

gem 'carrierwave', '~> 1.0' 

Add方法size_range提供最小尺寸和最大尺寸

class ImageUploader < CarrierWave::Uploader::Base 
    def size_range 
    0..2.megabytes 
    end 

在模型添加validates_integrity_of到一個有效的文件大小(和內容類型)圖片。

class Image < ApplicationRecord 
    mount_uploader :image, ImageUploader 

    validates_integrity_of :image