10

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" if uploadfile.size > 1.megabytes
end
Hishalv
  • 3,052
  • 3
  • 29
  • 52

3 Answers3

17

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.

Lucas
  • 2,886
  • 1
  • 27
  • 40
  • hi, i have edited my code above, however i get an error undefined local variable or method `uploadfile', any thoughts. iam not using carrierwave or paperclip, i am uploading directly to s3. – Hishalv Jun 22 '11 at 14:13
  • Try something like `"!uploadfile.blank?"` instead of `"uploadfile?"` - I think `picture?` is a method defined by CarrierWave – Lucas Jun 22 '11 at 17:01
  • thanks for the help, i finally installed carrierwave, as things were not working out, after some time i got the above code snippet to work, thanks again. – Hishalv Jun 23 '11 at 12:28
  • Does this size of the file get checked before or after the file is uploaded? – toy Jul 04 '11 at 21:25
  • Before uploading. I just checked right now because I had a doubt but it works fine. – Lucas Jul 04 '11 at 21:51
  • Rails 5: `..., if: -> { picture }` – Andrey Apr 26 '18 at 15:31
10

You can use:

validates_size_of :picture, maximum: 1.megabytes, message: "should be less than 1MB"
sudo
  • 1,581
  • 1
  • 10
  • 11
2

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 ...

NoDisplayName
  • 15,246
  • 12
  • 62
  • 98