0

我的模型看起来像:

class Art < ActiveRecord::Base
  attr_accessible :image
  has_attached_file :image, :styles => { :medium => "620x620>", :thumb => "200x200>" }
  validates_attachment :image, :content_type =>  { :content_type => "image/png" }
end

它验证并允许我上传 PNG 文件 png_file.png 并且不允许我上传 JPG 文件 jpg_file.jpg。

但是,如果我将 PNG 文件重命名为 png_file.jpg,它不允许我上传图像。如果我将 JPG 文件重命名为 jpg_file.png 它会错误地成功上传文件。

我想知道如何通过其真实内容而不是文件扩展名来验证上传的文件。有谁知道如何解决这个问题?

4

1 回答 1

2

您可以读取原始二进制文件并检查它是否为 PNG 类型:

File.open('path-to-your-file', 'rb').read(9).include?('PNG')

9是文件的幻

于 2013-11-14T01:18:35.017 回答