自定义验证文件大小在铁轨上载前 [英] Custom validation for file size in rails before being uploaded
本文介绍了自定义验证文件大小在铁轨上载前的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的形式,我有
<%= label_tag(文件,附件)%><%= file_field_tag一个UploadFile%>
在我的模型我想写这
验证:validates_uploadfile
高清validates_uploadfile(文件)
MAX_SIZE = 2048
errors.add(:uploadfile,文件大小超过限制),如果file.size> MAX_SIZE
结束
在我的控制器可我叫这样的事情
validates_upload_file(PARAMS [:uploadfile])
有没有办法来验证文件上传被上传(不使用JavaScript或通过查看文件扩展名)之前
感谢您的帮助
UPD
验证:uploadfile_validation,:如果=> 上传文件?
高清uploadfile_validation
错误[:uploadfile]<< 应小于1MB如果uploadfile.size> 1.megabytes
结束
解决方案
下面是我的code尺寸为验证(我用 CarrierWave 一>上载)。
验证:picture_size_validation,:如果=> 图片?
高清picture_size_validation
错误[:图片]<< 应小于1MB如果picture.size> 1.megabytes
结束
干杯。
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
解决方案
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.
这篇关于自定义验证文件大小在铁轨上载前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文