当文件不是有效的附件内容类型时,Paperclip :: NotIdentifiedByImageMagickError

时间:2010-01-21 18:15:32

标签: ruby-on-rails attachment paperclip

当我尝试上传不在["image/jpg", "image/jpeg", "image/gif", "image/png", "image/pjpeg", "image/x-png"]

中的文件时,我系统地出错了

当我尝试上传像'wav'这样的文件时,我有这条消息

* Photo /var/folders/nT/nTr21TWfFRO7r3cyG-h-7++++TM/-Tmp-/Clip audio 01,39154,0.wav is not recognized by the 'identify' command. * Photo /var/folders/nT/nTr21TWfFRO7r3cyG-h-7++++TM/-Tmp-/Clip audio 01,39154,0.wav is not recognized by the 'identify' command. * Photo content type Accepted files include: jpg, gif, png

因此,它检测到该文件不是图像并显示我的消息"Accepted files include: jpg, gif, png",但是在我的照片未被'identify'命令识别之前我已经包含了这个额外的消息... 上传适用于图片

我的代码是:

控制器:

def upload  
  @picture= Picture.new(params[:picture])  
    if !@picture.valid?  
        render  :form  
    end  
end  

查看表单

<%= error_messages_for :picture, :header_message => nil, :message => nil %>  
<% form_for :picture, @picture, :name => "uploadPic", :url => { :action => 'upload_data'}, :html => {:name => 'uploadForm', :multipart => true } do |form| %>  
    <%= form.file_field :photo %>  
    <%= submit_tag 'Save'%>  
<% end %>

图片模型:

 class Picture < ActiveRecord::Base    
    require 'paperclip'  
    has_attached_file :photo, :styles => { :medium => "300x300>", :thumb => "100x100>" }  

    validates_attachment_size :photo, :less_than => 2.megabytes , :message => "must be less than 2 megabytes"  
    validates_attachment_content_type :photo, :content_type => ["image/jpg", "image/jpeg", "image/gif", "image/png", "image/pjpeg", "image/x-png"], :message => "Accepted files include: jpg, gif, png"   

 end

2 个答案:

答案 0 :(得分:7)

解决它:whiny =&gt;假
    has_attached_file:photo,:whiny =&gt; false,:styles =&gt; {:medium =&gt; “300x300&gt;”,:thumb =&gt; “100×100&gt;” 中}

答案 1 :(得分:3)

:whiny =&gt; false不足以解决最新版回形针(2.3.6)的问题。我最终在rails初始化器中执行此操作:

module Paperclip
  class Attachment
    alias original_assign assign
    def assign(*args)
      original_assign(*args)
    rescue NotIdentifiedByImageMagickError => e
    end
  end
end

似乎可以吞下该异常,因为至少在您使用时,无论如何都会添加验证错误:whiny =&gt;真。