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

时间:2012-01-11 11:12:11

标签: ruby-on-rails-3 paperclip

在我的模特中:

 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或text docs。请帮助我,我失踪了!

4 个答案:

答案 0 :(得分:44)

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

答案 1 :(得分:2)

查看Validate extension in Paperclip - Ruby on Rails(在接受的答案中)

答案 2 :(得分:2)

这实际上取决于您的服务器' file'命令。该命令返回给您的是您需要在回形针验证中接受的内容。

例如我的Debian服务器返回" application / msword"对于xls文件。对于xlsx文件,它提供" application / zip"。

我目前有这些接受xls和xlsx文件。

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 :(得分:0)

对于任何文件,如果您要上传,如果您不知道其中的内容类型,请使用该文档自行检出上传,然后在开发日志(或终端)中检查它是哪个content_type。然后更改应用程序中的content_type。