上传前对 Rails 中的文件大小进行自定义验证 [英] Custom validation for file size in rails before being uploaded

查看:20
本文介绍了上传前对 Rails 中的文件大小进行自定义验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的表单中我有

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])

有没有办法在上传之前验证文件上传(不是使用javascript或查看文件扩展名)
感谢您的帮助

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

推荐答案

这是我的尺寸验证代码(我使用 CarrierWave 用于上传).

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

干杯.

这篇关于上传前对 Rails 中的文件大小进行自定义验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆