<%= form_for @model_name, :url => {:controller => 'controller_name', :action => 'index'},:html => {:multipart => true},:validate => true do |f| %>
<%= file_field 'upload', 'datafile'%>
<% end %>
我有这个表格。我想通过此上传仅上传图片。怎么做?
答案 0 :(得分:7)
HTML5
<%= f.file_field :file, multiple: true, accept:'image/*' %>
答案 1 :(得分:1)
您可以使用paperclip gem来管理文件附件。它有validates_attachment
验证器,这将有所帮助。
validates_attachment :avatar, :presence => true,
:content_type => { :content_type => "image/jpg" },
:size => { :in => 0..10.kilobytes }
答案 2 :(得分:0)
您仍然可以根据内容类型进行简单验证:
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
显然你可以调整正则表达式,具体取决于你想接受什么类型的图像。