如何将文件内容类型验证为回形针的pdf,word,excel和纯文本?

Rav*_*dra 19 paperclip ruby-on-rails-3

在我的模型中:

 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. '
Run Code Online (Sandbox Code Playgroud)

在此之后,它只能上传PDF文档,而不是excel或文字或文本文档.请帮助我,我失踪了!

eng*_*nky 45

我不知道您是否已经为自己解决了这个问题,但是您缺少要处理的文档的MIME类型尝试更改:content_type为:

:content_type => ["application/pdf","application/vnd.ms-excel",     
             "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
             "application/msword", 
             "application/vnd.openxmlformats-officedocument.wordprocessingml.document", 
             "text/plain"]
Run Code Online (Sandbox Code Playgroud)

或使用自定义验证

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
Run Code Online (Sandbox Code Playgroud)