How to validate file content type to pdf, word, excel, and plain text for paperclip?

只愿长相守 提交于 2019-12-04 08:59:24

问题


In my model:

 has_attached_file :uploaded_file,  
                      :url => "/policy_documents/get/:id",  
                      :path => "/public/policy_documents/:id/:basename.:extension" 

    validates_attachment_size :uploaded_file, :less_than => 10.megabytes    
    validates_attachment_presence :uploaded_file 
     validates_attachment_content_type :uploaded_file, :content_type =>['application/pdf', 'application/xlsx'],
                                                       :message => ', Only PDF, EXCEL, WORD or TEXT files are allowed. '

And after this, it can upload only PDF documents, not excel or word or text docs. Please help me where I am missing!


回答1:


I don't know if you have solved this for yourself but you are missing MIME types for the documents you want to handle try changing :content_type to:

:content_type => ["application/pdf","application/vnd.ms-excel",     
             "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
             "application/msword", 
             "application/vnd.openxmlformats-officedocument.wordprocessingml.document", 
             "text/plain"]

Or use a custom validation

validate :correct_content_type, :message => ", Only PDF, EXCEL, WORD or TEXT files are allowed."


def correct_content_type 
  acceptable_types = ["application/pdf","application/vnd.ms-excel",     
             "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
             "application/msword", 
             "application/vnd.openxmlformats-officedocument.wordprocessingml.document", 
             "text/plain"]
  acceptable_types.include? uploaded_file.content_type.chomp
end



回答2:


This is actually dependent on your servers 'file' command. What that command returns to you is what you need to be accepting in the paperclip validations.

For example my Debian server returns "application/msword" for an xls file. And for an xlsx file it gives "application/zip".

I currently have these to accept xls and xlsx files.

validates_attachment_content_type :file, :content_type => %w(application/zip application/msword application/vnd.ms-office application/vnd.ms-excel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet)



回答3:


For any files if you are uploading, if you don't know the content type of that means, checkout uploading with that document itself, and after this, check in the development log(or terminal) which content_type it is...then change that content_type in your application.



来源:https://stackoverflow.com/questions/8818251/how-to-validate-file-content-type-to-pdf-word-excel-and-plain-text-for-paperc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!