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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With