5
<%= form_for @model_name, :url => {:controller => 'controller_name', :action => 'index'},:html => {:multipart => true},:validate => true do |f| %>

<%= file_field 'upload', 'datafile'%>

<% end %>

我有这个表格。我想通过这个上传只上传图片。这个怎么做?

4

3 回答 3

13

HTML5

<%= f.file_field :file, multiple: true, accept:'image/*' %>
于 2016-01-27T05:18:31.327 回答
1

您可以使用回形针gem 来管理文件附件。它有validates_attachment验证器,这会很有帮助。

validates_attachment :avatar, :presence => true,
  :content_type => { :content_type => "image/jpg" },
  :size => { :in => 0..10.kilobytes }
于 2012-06-05T11:32:39.943 回答
1

您仍然可以根据内容类型进行简单的验证:

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

显然,您可以根据要接受的图像类型来调整正则表达式。

于 2012-06-05T11:41:44.560 回答