Rails如何验证文件格式?

时间:2021-09-05 22:29:44

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

如何验证文件字段以获得正确的格式?

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

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

And the flv that it has the ending .flv

它的结尾是。flv

And the quicktime that it have the ending .mov

很快,它就以。mov结尾了

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

如何创建错误消息以告知字段无效。

My simple_form_for:

我的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' %>

Update:

更新:

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

我已经知道如何验证.mov和.flv字段:

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.

´我不找到了一个解决方案来验证图像。

My controller:

我的控制器:

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         

1 个解决方案

#1


9  

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

如果你想继续使用flv和mov,你可以:

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

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

但是请注意,这只会验证文件名将以特定的字符串结尾。这些不验证实际的文件是一个真正的PNG(或任何格式)。因此,有人仍然可以上传一个带有扩展名“。png”的zipfile。

#1


9  

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

如果你想继续使用flv和mov,你可以:

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

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

但是请注意,这只会验证文件名将以特定的字符串结尾。这些不验证实际的文件是一个真正的PNG(或任何格式)。因此,有人仍然可以上传一个带有扩展名“。png”的zipfile。