Ruby on Rails - Active Storage - 如何只接受pdf和doc?

问题描述 投票:7回答:7

是否可以添加验证以仅使用Active Storage接受.pdf和.doc文件?

ruby-on-rails ruby-on-rails-5 rails-activestorage
7个回答
13
投票

目前,您必须编写自己的验证程序,查看附件的MIME类型:

class Item
  has_one_attached :document

  validate :correct_document_mime_type

  private

  def correct_document_mime_type
    if document.attached? && !document.content_type.in?(%w(application/msword application/pdf))
      document.purge # delete the uploaded file
      errors.add(:document, 'Must be a PDF or a DOC file')
    end
  end
end

此外,还有一些有用的快捷方法image?audio?video?text?可以检查多种mime类型。


6
投票

有一个gem可以为主动存储提供验证

gem 'activestorage-validator'

https://github.com/aki77/activestorage-validator

  validates :avatar, presence: true, blob: { content_type: :image }
  validates :photos, presence: true, blob: { content_type: ['image/png', 'image/jpg', 'image/jpeg'], size_range: 1..5.megabytes }

2
投票

由于ActiveStorage还没有验证,我在表单中发现了以下帮助。

<div class="field">
  <%= f.label :deliverable %>
  <%= f.file_field :deliverable, direct_upload: true, 
    accept: 'application/pdf, 
    application/zip,application/vnd.openxmlformats-officedocument.wordprocessingml.document' %>
 </div>

1
投票
class Book < ApplicationRecord
  has_one_attached :image
  has_many_attached :documents

  validate :image_validation
  validate :documents_validation

  def documents_validation
    error_message = ''
    documents_valid = true
    if documents.attached?
      documents.each do |document|
        if !document.blob.content_type.in?(%w(application/xls application/odt application/ods pdf application/tar application/tar.gz application/docx application/doc application/rtf application/txt application/rar application/zip application/pdf image/jpeg image/jpg image/png))
          documents_valid = false
          error_message = 'The document wrong format'
        elsif document.blob.byte_size > (100 * 1024 * 1024) && document.blob.content_type.in?(%w(application/xls application/odt application/ods pdf application/tar application/tar.gz application/docx application/doc application/rtf application/txt application/rar application/zip application/pdf image/jpeg image/jpg image/png))
          documents_valid = false
          error_message = 'The document oversize limited (100MB)'
        end
      end
    end
    unless documents_valid
      errors.add(:documents, error_message)
      self.documents.purge
      DestroyInvalidationRecordsJob.perform_later('documents', 'Book', self.id)
    end
  end

  def image_validation
    if image.attached?
      if !image.blob.content_type.in?(%w(image/jpeg image/jpg image/png))
        image.purge_later
        errors.add(:image, 'The image wrong format')
      elsif image.blob.content_type.in?(%w(image/jpeg image/jpg image/png)) && image.blob.byte_size > (5 * 1024 * 1024) # Limit size 5MB
        image.purge_later
        errors.add(:image, 'The image oversize limited (5MB)')
      end
    elsif image.attached? == false
      image.purge_later
      errors.add(:image, 'The image required.')
    end
  end
end

并在工作中摧毁

class DestroyInvalidationRecordsJob < ApplicationJob
  queue_as :default

  def perform(record_name, record_type, record_id)
    attachments = ActiveStorage::Attachment.where(name: record_name, record_type: record_type, record_id: record_id)
    attachments.each do |attachment|
      blob = ActiveStorage::Blob.find(attachment.blob_id)
      attachment.destroy
      blob.destroy if blob.present?
    end
  end
end

0
投票

我正在使用ActiveStorage直接上传。由于验证器不存在,我只是覆盖了DirectUploadsController Create方法:

# This is a kind of monkey patch which overrides the default create so I can do some validation.
# Active Storage validation wont be released until Rails 6.
class DirectUploadsController < ActiveStorage::DirectUploadsController
  def create
    puts "Do validation here"
    super
  end
end

还需要覆盖路线:

  post '/rails/active_storage/direct_uploads', to: 'direct_uploads#create'

0
投票

使用gem 'activestorage-validator'和ActiveStorage的+1

在您的模型中,您可以通过以下方式验证docdocxpdf格式:

has_one_attached :cv
validates :cv, blob: { content_type: ['application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/pdf'], size_range: 0..5.megabytes }

0
投票

我在看https://gist.github.com/lorenadl/a1eb26efdf545b4b2b9448086de3961d

看起来你的观点就像这样

<div class="field">
  <%= f.label :deliverable %>
  <%= f.file_field :deliverable, direct_upload: true, 
    accept: 'application/pdf, 
    application/zip,application/vnd.openxmlformats-officedocument.wordprocessingml.document' %>
 </div>

现在在你的模型上,你可以做这样的事情

class User < ApplicationRecord
  has_one_attached :document

  validate :check_file_type

  private

  def check_file_type
    if document.attached? && !document.content_type.in?(%w(application/msword application/pdf))
      document.purge # delete the uploaded file
      errors.add(:document, 'Must be a PDF or a DOC file')
    end
  end
end

我希望这个对你有用

© www.soinside.com 2019 - 2024. All rights reserved.