Ruby 在 rails。回形针 mp3 验证失败

Ruby on rails. Paperclip mp3 validation failing

好的,我允许用户上传 mp3。现在出于某种原因,只有一些 mp3 文件会上传,而其他的则不会。我找不到工作文件和非工作文件之间的任何明显区别。

class Song < ActiveRecord::Base
  belongs_to :user
  has_attached_file :audio, :restricted_characters => /[&$+,\/:;=?@<>\[\]\{\}\|\\^~%#]/, dependent: :destroy
  validates_attachment_presence :audio
  validates_attachment_content_type :audio, :content_type => [ 'audio/mpeg', 'audio/mp3' ]
  validates_attachment_size :audio, :less_than => 20.megabytes
end

失败文件的服务器输出是;

Command :: file -b --mime '/tmp/acf7bcfce06ffcaa55511087ea2e486f20160427-7322-y1lyj6.mp3'
[paperclip] Content Type Spoof: Filename leyinnata.mp3 (audio/mp3 from Headers, ["audio/mpeg"] from Extension), content type discovered from file command: application/octet-stream. See documentation to allow this combination.

所以文件被视为 application/octet-stream 而不是 audio/mp3,我不知道为什么。

我听从了阅读文档的建议并找到了可能的解决方案:

paperclip.rb

Paperclip.options[:content_type_mappings] = {
  :audio=> 'application/octet-stream'
}

这没有任何作用。 (我重启了服务器)

我不明白为什么它不起作用,我现在感到非常沮丧。如有任何帮助,我们将不胜感激。

更新:

指定更多的音频文件类型似乎没有任何区别。

validates_attachment_content_type :audio, :content_type => [ 'audio/mpeg', 'audio/x-mpeg', 'audio/mp3', 'audio/x-mp3', 'audio/mpeg3', 'audio/x-mpeg3', 'audio/mpg', 'audio/x-mpg', 'audio/x-mpegaudio' ]

我也试过将 application/octet-stream 添加到 validates_attachment_content_type 例如。

validates_attachment_content_type :audio, :content_type => [ 'application/octet-stream', 'audio/mpeg', 'audio/x-mpeg', 'audio/mp3', 'audio/x-mp3', 'audio/mpeg3', 'audio/x-mpeg3', 'audio/mpg', 'audio/x-mpg', 'audio/x-mpegaudio' ]

运气不好。

看到有人加

Paperclip.options[:content_type_mappings] = {
  audio: "application/octet-stream"
}

到他们的 environment.rb 文件。这对我也不起作用。

更新 2:

在paperclip.rb中添加:

module Paperclip
  # do not require any validations
  REQUIRED_VALIDATORS = []

  # do not complain when missing validations
  class Attachment
    def missing_required_validator?
      false
    end
  end

  # skip media type spoof detection
  module Validators
    class MediaTypeSpoofDetectionValidator < ActiveModel::EachValidator
      def validate_each(record, attribute, value)
        true
      end
    end
  end
end

让我上传我需要的东西,但这会跳过欺骗验证,我想这可能很危险。我的用户也可以在网站的单独部分上传图片,我知道我现在很容易受到攻击。

更新 3:

我已经添加了

module Paperclip
  class MediaTypeSpoofDetector
    def spoofed?
      false
    end
  end
end

给我的 paperclip.rb。这似乎工作正常。如果有人能提出更好的解决方案,那么我很乐意听到,否则我会回答我自己的问题。

也许您必须更加具体地进行 mp3 类型验证。 举个例子,

你应该

validates_content_type :audio :content_type => [ 'audio/mpeg', 'audio/x-mpeg', 'audio/mp3', 'audio/x-mp3', 'audio/mpeg3', 'audio/x-mpeg3', 'audio/mpg', 'audio/x-mpg', 'audio/x-mpegaudio' ]

希望这能解决您的问题。请告诉我们。

我通过删除我放在 'updates' 中的所有内容并添加:

解决了这个问题
Paperclip.options[:content_type_mappings] = {
  mp3: 'application/octet-stream'
}

paperclip.rb