Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails content-type for file_field uploads is incorrect

We have a file upload for pdf documents using the rails helper file_field in our system. We started with rails 2, and now rails 3 for about a year.

Looking in our database the pdf content/type is all over the place.

My understanding is it should always be application/pdf

but here is the list of types we have received:

application/x-octetstream
application/octet
application/x-download
binary/octet-stream
text/html
application/application/pdf
application/download
application/x-download
text/javascript
text/html
text/csv

The only work around I can see to set the content type correctly for now is to inspect the file body (something like this)

 if (upload_doc_name_ext == "pdf") && (incoming_file.content_type != "application/pdf") && (incoming_file[0..10].match(/%PDF-/) != nil)
    incoming_file.content_type = 'application/pdf'
 end

Any other ideas? Is this normal, is something else weird going on? Are the browsers behaving properly?

like image 320
Joelio Avatar asked May 28 '14 20:05

Joelio


1 Answers

by default, rails form helper: file_field allows to upload all MIME filetypes so this is the reason why you have all those listed above.

In rails, if you use file_field_tag or form.file_field, you can specify the mime/content_type using accept option and list there all types user can upload.

:accept - If set to one or multiple mime-types, the user will be suggested a filter when choosing a file. You still need to set up model validations.

Source:

http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-file_field

Anyway, I suggest to use paperclip gem and specify content_type validation then.

class ActiveRecord::Base
  has_attached_file :document
  # Validate content type
  validates_attachment_content_type :document, :content_type => /\Aapplication\/pdf/
end

Paperclip would be easier to use and manage uploaded filetypes, it allow to adjust many oprions for uploading, so if you updated your application to Rails 3, it wolud be good solution for you.

Vote if it will help.

like image 81
swilgosz Avatar answered Oct 14 '22 04:10

swilgosz