ActiveStorage 文件附件验证 [英] ActiveStorage File Attachment Validation

查看:27
本文介绍了ActiveStorage 文件附件验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法用 ActiveStorage 验证附件?例如,如果我想验证内容类型或文件大小?

Is there a way to validate attachments with ActiveStorage? For example, if I want to validate the content type or the file size?

类似 Paperclip 的方法会很棒!

Something like Paperclip's approach would be great!

  validates_attachment_content_type :logo, content_type: /\Aimage\/.*\Z/
  validates_attachment_size :logo, less_than: 1.megabytes

推荐答案

好吧,它并不漂亮,但在他们进行一些验证之前这可能是必要的:

Well, it ain't pretty, but this may be necessary until they bake in some validation:

  validate :logo_validation

  def logo_validation
    if logo.attached?
      if logo.blob.byte_size > 1000000
        logo.purge
        errors[:base] << 'Too big'
      elsif !logo.blob.content_type.starts_with?('image/')
        logo.purge
        errors[:base] << 'Wrong format'
      end
    end
  end

这篇关于ActiveStorage 文件附件验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆