4

我是 Paperclip 的新手,一切似乎都运行得很快。我试图让用户只上传 PNG 或 JPG,虽然我正在上传 JPG 并且我的 content_type 验证了 JPG,但它仍然说它是无效的。

我尝试删除 PNG content_type,但无济于事。

我也尝试过使用has_attached_file,但它似乎忽略了 :content_type 和其他东西。因为如果我:content_type => "image/png"只上传 JPG;它不会给出错误。

有什么建议么?

    validates_attachment :avatar, :styles => { 
                                    :medium => "300x300", 
                                    :thumb => "100x100" 
                                }, :content_type => { 
                                    :content_type => "image/jpg", 
                                    :content_type => "image/png"
                                },
                                :size => { :in => 0..1.megabytes }

哦,当我在做的时候;我想让我的拇指和中号达到固定宽度。所以没有像 100x80 这样的缩放,但无论哪种方式都只有 100x100。我怎样才能做到这一点?

4

3 回答 3

5

您似乎正在尝试使用一些Paperclip validation,您可以在这里查看:Paperclip - Validate File Type but not Presence

根据那个答案,你可以使用这个:

validates_attachment_content_type :sound, :content_type => ['audio/mp3', 'application/x-mp3'], :if => :sound_attached?

另一种方法是用于lambda检查您是否正在处理特定的内容类型。这是我们的一个实时应用程序的示例:

   has_attached_file :attachment,
            styles:          lambda { |a| a.instance.is_image? ? {:small => "x200>", :medium => "x300>", :large => "x400>"}  : {:thumb => { :geometry => "100x100#", :format => 'jpg', :time => 10}, :medium => { :geometry => "300x300#", :format => 'jpg', :time => 10}}}

    def is_image?
            attachment.instance.attachment_content_type =~ %r(image)
    end

Lambda 只是一种衡量是否content-type是您需要的方法(即您只允许 JPG 图像)。为了验证图像(而不是视频)的存在,您需要validates_attachment_content_type

于 2013-11-11T09:26:38.100 回答
3

我今晚遇到了同样的问题,结果我需要 image/jpeg 和 image/jpg

 validates_attachment :avatar, :styles => { 
                                    :medium => "300x300", 
                                    :thumb => "100x100" 
                                }, :content_type => { 
                                    :content_type => "image/jpg",
                                    :content_type => "image/jpeg", 
                                    :content_type => "image/png"
                                },
                                :size => { :in => 0..1.megabytes }

它在尝试 /^image/ 时有效,但我喜欢具体。

于 2014-01-04T23:47:20.643 回答
0

我比较了来自服务器的日志,并注意到内容类型标头的不同。它应该是“图像/JPEG”

Parameters: {"avatar"=>#<ActionDispatch::Http::UploadedFile:0x0055b7d4c30870 @tempfile=#<Tempfile:/tmp/RackMultipart20170510-21515-11ld4ji.jpg>, @original_filename="IMAG0303.jpg", @content_type="multipart/form-data", @headers="Content-Disposition: form-data; name=\"avatar\"; filename=\"IMAG0303.jpg\"\r\nContent-Type: multipart/form-data\r\nContent-Length: 1057779\r\n">}

Parameters: {"avatar"=>#<ActionDispatch::Http::UploadedFile:0x0055b7d3ec3408 @tempfile=#<Tempfile:/tmp/RackMultipart20170510-21515-1l0x8sw.jpg>, @original_filename="2017.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"avatar\"; filename=\"photo_10/05/2017.jpg\"\r\nContent-Type: image/jpeg\r\n">}
于 2017-05-10T04:03:26.700 回答