Rails 如何验证文件格式? [英] Rails how to validate file format?

查看:74
本文介绍了Rails 如何验证文件格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何验证我的文件字段的格式是否正确?

How do I validate my file fields for the correct format?

我希望图像字段验证它是 .png、.jpg、.jpeg.

I want the image field to validate that it is a .png, .jpg, .jpeg.

还有以.flv结尾的flv

And the flv that it has the ending .flv

还有以 .mov 结尾的 quicktime

And the quicktime that it have the ending .mov

以及如何创建错误消息以告知该字段无效.

And how do I create error messages to tell that the field is not valid.

我的 simple_form_for:

My simple_form_for:

<%= f.input :name, :label => 'Navn', :required => true %><br />
<%= f.label :tekst %><br />
<%= f.text_area :text, :label => 'Text', :size => '12x12' %><br />
<%= f.label "Upload billede - kræves" %><br />
<%= f.input :image, :label => '', :required => true %><br />
<%= f.label "Upload flv - kræves" %><br />
<%= f.input :flv, :label => '', :required => true %><br />
<%= f.label "Upload Quicktime - kræves"  %><br />
<%= f.input :quicktime, :label => '', :required => true %><br />
<%= f.button :submit, :value => 'Create movie' %>

更新:

我已经弄清楚如何验证 .mov 和 .flv 字段:

I have figure out how to validate the .mov and .flv fields:

validates_format_of :flv, 
:with => %r{\.flv$}i, :message => "file must be in .flv format"

validates_format_of :mov, 
:with => %r{\.mov$}i, :message => "file must be in .mov format"

我只是没有找到验证图像的解决方案.

I just don´t have found a solution to validate the image.

我的控制器:

def savenew
    @photographer = Photographer.new(params[:photographer]) 
    @photographer.sort_order = Photographer.count + 1

    if @photographer.save   
      redirect_to :action => 'list', :id => params[:id]
      flash[:notice] = "Movie #{@photographer.name} is created"
    else    
      render 'create', :id => params[:id]             
    end                                 
end         

推荐答案

如果你想像 flv 和 mov 一样继续,你可以这样做:

If you want to continue as with flv and mov, you could do:

validates_format_of :image, :with => %r{\.(png|jpg|jpeg)$}i, :message => "whatever"

但是请注意,这只会验证文件名是否以特定字符串结尾.这些不会验证实际文件是否为真正的 PNG(或任何格式).所以有人仍然可以上传一个扩展名为.png"的压缩文件.

but please be aware that this would only validate that the filename would end in a specific string. These don't validate that the actual file is a real PNG (or whatever format). So someone could still just upload a zipfile with extension ".png".

这篇关于Rails 如何验证文件格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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