好的,我允许用户上传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
文件进行了一些修改,目前似乎运行良好。如果有更好的解决方案,请分享,否则我将自己回答这个问题。