2011-01-20 86 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