【问题标题】:Rails Paperclip content type validation by exclusionRails Paperclip 内容类型通过排除验证
【发布时间】:2016-08-30 01:07:04
【问题描述】:

我正在开发一个供我们内部使用的消息传递系统,每条消息都可以有附件。所述附件几乎可以是任何类型的文件,但我不想允许某些类型的文件,例如 EXE。

与其在模型验证中列出大量已接受的 content_types,这远非实用,而且肯定会阻止应该接受的文件,我宁愿简单地指定应该的内容类型被接受。

谷歌搜索没有产生任何结果,但我敢肯定其他人以前遇到过这种情况,知道如何最好地解决这个问题吗?

【问题讨论】:

    标签: ruby-on-rails-4 paperclip


    【解决方案1】:

    所以这就是我最终要做的:

    has_mongoid_attached_file :file
    
    do_not_validate_attachment_file_type :file
    validate :excluded_content_type
    
    def excluded_content_type
      forbidden = [
        "application/x-msdownload",
        "application/x-ms-installer",
        "application/x-elf",
        "application/x-sh",
        "application/x-shellscript",
        "text/x-perl",
        "text/x-python",
        "application/javascript"
      ]
      errors.add(:base, 'Executable and script files are not allowed.') if forbidden.include? file_content_type
    end
    

    我不知道这是否是最好的方法,但它确实有效。如果您有更好的方法,请发布您的答案!

    【讨论】:

      【解决方案2】:

      如果内容类型应该不被接受

      写入model.rb

        has_attached_file :record_attachment      
        validates_attachment_content_type :record_attachment, presence: false, :content_type => {:not => "application/zip"}
      

      【讨论】:

      • 请编辑更多信息。不建议使用纯代码和“试试这个”的答案,因为它们不包含可搜索的内容,也没有解释为什么有人应该“试试这个”。
      猜你喜欢
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 1970-01-01
      • 2016-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多