Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/58.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何限制仅通过文件\字段标记上载图像? {:controller=>'controller_name',:action=>'index'},:html=>{:multipart=>true},:validate=>true do | f |%>_Ruby On Rails_Ruby_Forms - Fatal编程技术网

Ruby on rails 如何限制仅通过文件\字段标记上载图像? {:controller=>'controller_name',:action=>'index'},:html=>{:multipart=>true},:validate=>true do | f |%>

Ruby on rails 如何限制仅通过文件\字段标记上载图像? {:controller=>'controller_name',:action=>'index'},:html=>{:multipart=>true},:validate=>true do | f |%>,ruby-on-rails,ruby,forms,Ruby On Rails,Ruby,Forms,我有这张表格。我只想通过这个上传上传图片。如何做到这一点?您可以使用gem管理文件附件。它有验证\u附件验证程序,这会很有帮助 <%= form_for @model_name, :url => {:controller => 'controller_name', :action => 'index'},:html => {:multipart => true},:validate => true do |f| %> <%= file_fi

我有这张表格。我只想通过这个上传上传图片。如何做到这一点?

您可以使用gem管理文件附件。它有
验证\u附件
验证程序,这会很有帮助

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

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

<% end %>

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

validates_attachment :avatar, :presence => true,
  :content_type => { :content_type => "image/jpg" },
  :size => { :in => 0..10.kilobytes }
classmymodels
显然,您可以根据希望接受的图像类型调整regexp。

HTML5

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

这将禁用在文件浏览器中选择非图像文件,但仍可以将文件拖放到“文件字段”按钮上。(在Chrome、Mac上测试)
<%= f.file_field :file, multiple: true, accept:'image/*' %>