ActiveStorage File Attachment Validation

前端 未结 7 535
暖寄归人
暖寄归人 2021-01-31 10:01

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

Something like Paperclip\'s approach wou

7条回答
  •  礼貌的吻别
    2021-01-31 10:29

    Copy contents of the ActiveStorage's DirectUploadsController in the app/controllers/active_storage/direct_uploads_controller.rb file and modify the create method. You can add authentication to this controller, add general validations on the file size or mime type, because create method of this controller creates the url for the file to be uploaded. So you can prevent any file upload by controlling size and mime type in this controller.

    A simple validation could be:

    # ...
    def create
      raise SomeError if blob_args[:byte_size] > 10240 # 10 megabytes
      blob = ActiveStorage::Blob.create_before_direct_upload!(blob_args)
      render json: direct_upload_json(blob)
    end
    # ...
    

提交回复
热议问题