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

后端 未结 3 1772
醉话见心
醉话见心 2021-02-05 07:44

In my model:

 has_attached_file :uploaded_file,  
                      :url => \"/policy_documents/get/:id\",  
                      :path => \"/public/p         


        
3条回答
  •  情书的邮戳
    2021-02-05 08:42

    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
    

提交回复
热议问题