Colin Wu
Colin Wu

Reputation: 699

paperclip 5.1 content-type validation too strict

I need to upload attachments with extension of .txt but evaluate to mime-type "application/octet-stream" by the file command. The file is automatically generated by a piece of equipment and it is not feasible to rename it before uploading. I have tried:

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

but I always get an error that the detected content-type does not match the inferred content-type:

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.

The error message says to look in documentation for a way to allow the combination but I have not been able to find anything that looks like a workaround. Saw this discussion but it was for v4.

Upvotes: 3

Views: 1857

Answers (2)

Colin Wu
Colin Wu

Reputation: 699

Thanks for the pointer, Chris. Guess I didn't read that section of the README file carefully enough. (BTW, fixing the typo didn't make any difference.)

So, the solution is as follows:

In config/initializers/paperclip.rb:

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

In the model:

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

This works whether the actual .txt file is a 'text/plain' or 'application/octet-stream'.

Upvotes: 3

Chris Peters
Chris Peters

Reputation: 18090

Is it because of the misspelled content_type key? (You have it entered as content_typ.)

If the first suggestion doesn't work, I think that in your case, you'd want to do this in config/initializers/paperclip.rb (according to instructions in the README's Security Validations section):

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

Upvotes: 3

Related Questions