开发者

Custom validation for file size in rails before being uploaded

in my form i have

<%= label_tag("file", "Attachment:") %><%= file_field_tag "uploadfile" %>

In my model i would like to write this

validate :validates_uploadfile

def validates_uploadfile(file)
    max_size = 2048
    errors.add(:uploadfile, "File size exceeds limitation") if file.size > max_size
end

In my controller can i call something like this

validates_upload_file(params[:uploadfile])

Is there a way to validate a file upload before being uploaded(not by using javascript or by looking at the file extension)

Thanks for the help

UPD

validate :uploadfile_validation, :if => "uploadfile?"

def uploadfile_validation
    errors[:uploadfile] << "should be less than 1MB" 开发者_Python百科if uploadfile.size > 1.megabytes
end


Here's my code for size validations (I use CarrierWave for uploads).

  validate :picture_size_validation, :if => "picture?"  

  def picture_size_validation
    errors[:picture] << "should be less than 1MB" if picture.size > 1.megabytes
  end

Cheers.


You can use:

validates_size_of :picture, maximum: 1.megabytes, message: "should be less than 1MB"


If I am not mistaken, then all those methods above check the file size once its been uploaded ( and maybe even processed ) but what happens if I choose a 1GB file in file input field for pictures considering that javascript validation is absent or javascript is just disabled? It probablt gets uploaded, taking a lot of time just to tell ya that its too big, that just aint right. I am a newbie so I might be wrong about something ...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜