How to validate/limit attachment file size

897 views Asked by At

In an Ecto model with attachment using arc and arc_ecto:

  use Arc.Ecto.Schema

  schema "profiles" do
    ...
    field :avatar, MyApp.AvatarUploader.Type
    ...

    timestamps()
  end

How can I validate/limit the size of the attachment? I read about it in the guides with the configuration of Plug.Parsers but I would like to do this at a model level and not at the application level. For instance the user avatar should be small but other picture should be larger.

What's the best way to achieve this?

1

There are 1 answers

0
Shunji Lin On

In case anyone is wondering, I believe can validate before storing the file in the module where you define your arc definitions: https://github.com/stavro/arc#file-validation

Something like the following:

def validate({%Arc.File{path: path}, _}) do
  %{size: size} = File.stat!(path)
  # less than 100 bytes
  size < 100
end

This should work with arc_ecto