<%= form_for @model_name, :url => {:controller => 'controller_name', :action => 'index'},:html => {:multipart => true},:validate => true do |f| %>
<%= file_field 'upload', 'datafile'%>
<% end %>
我有这个表格。我想通过这个上传只上传图片。这个怎么做?
<%= form_for @model_name, :url => {:controller => 'controller_name', :action => 'index'},:html => {:multipart => true},:validate => true do |f| %>
<%= file_field 'upload', 'datafile'%>
<% end %>
我有这个表格。我想通过这个上传只上传图片。这个怎么做?
HTML5
<%= f.file_field :file, multiple: true, accept:'image/*' %>
您可以使用回形针gem 来管理文件附件。它有validates_attachment
验证器,这会很有帮助。
validates_attachment :avatar, :presence => true,
:content_type => { :content_type => "image/jpg" },
:size => { :in => 0..10.kilobytes }
您仍然可以根据内容类型进行简单的验证:
class MyModels < ActiveRecord::Base
validate :upload_is_image
...
private
def upload_is_image
unless upload and upload.content_type =~ /^image\/(jpeg|pjpeg|gif|png|bmp)$/
errors.add(:upload, "Not a valid image")
end
end
end
显然,您可以根据要接受的图像类型来调整正则表达式。