本文介绍了如何将文件内容类型验证为 pdf、word、excel 和用于回形针的纯文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的模型中:

 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. '

此后,它只能上传PDF文档,不能上传excel或word或文本文档.请帮我找我失踪的地方!

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

推荐答案

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

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"]

或使用自定义验证

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

这篇关于如何将文件内容类型验证为 pdf、word、excel 和用于回形针的纯文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-02 19:37