1

我需要上传扩展名为 .txt 的附件,但通过 file 命令评估为 mime 类型“application/octet-stream”。该文件是由一台设备自动生成的,上传前无法重命名。我努力了:

class Book < ActiveRecord::Base
  has_attached_file :excerpt
  validates_attachment_content_type :excerpt, content_type: { content_typ: ["text/plain", "application/octet-stream"]}
  validates_attachment_file_name :excerpt, matches: [/txt\z/]
end

但我总是收到一个错误,即检测到的内容类型与推断的内容类型不匹配:

Command :: file -b --mime '/tmp/313a40bb0448477e051da1e2cba2c20120161027-19345-lrhf6t.txt'
[paperclip] Content Type Spoof: Filename Sample.txt (text/plain from Headers, ["text/plain"] from Extension), content type discovered from file command: application/octet-stream. See documentation to allow this combination.

错误消息说要在文档中查找允许组合的方法,但我找不到任何看起来像解决方法的方法。看到了这个讨论,但它是针对 v4 的。

4

2 回答 2

2

谢谢你的指点,克里斯。我想我没有足够仔细地阅读 README 文件的那部分。(顺便说一句,修正错字没有任何区别。)

因此,解决方案如下:

config/initializers/paperclip.rb

Paperclip.options[:content_type_mappings] = {
  txt: %w(application/octet-stream)
}

在模型中:

class Book < ActiveRecord::Base
  has_attached_file :excerpt
  validates_attachment_file_name :excerpt, matches: [/txt\z/]
end

无论实际的 .txt 文件是“text/plain”还是“application/octet-stream”,这都有效。

于 2016-10-28T01:46:04.440 回答
2

是因为content_type钥匙拼错了吗?(您将其输入为content_typ。)

如果第一个建议不起作用,我认为在您的情况下,您希望在config/initializers/paperclip.rb(根据自述文件的安全验证部分中的说明)执行此操作:

Paperclip.options[:content_type_mappings] = {
  txt: %w(text/plain application/octet-stream)
}
于 2016-10-27T21:29:26.067 回答