ruby-on-rails-3 – 如何验证文件内容类型为pdf,word,excel和纯文本?

前端之家收集整理的这篇文章主要介绍了ruby-on-rails-3 – 如何验证文件内容类型为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或文本文档.请帮我我失踪的地方

解决方法

我不知道你是否为自己解决了这个问题,但是你想要处理的文档缺少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"]

或使用自定义验证

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


def correct_content_type 
  acceptable_types = ["application/pdf","text/plain"]
  acceptable_types.include? uploaded_file.content_type.chomp
end
原文链接:https://www.f2er.com/ruby/272622.html

猜你在找的Ruby相关文章