adanselm
adanselm

Reputation: 345

How to upload a big file from a form to Phoenix?

I have an HTML form with a file field that is used to upload a file to a /file route in my Phoenix application.

I mimic this behaviour from command line with curl -v -F "file=@MyTestFile" http://localhost:4000/file/ for faster testing.

When I use a big file (turning point seems to be around 7.7MB), I get the following exception from Plug:

18:40:38.897 [error] Error in process <0.420.0> with exit value: {[{reason,#{'exception'=>true,'struct'=>'Elixir.Plug.Parsers.RequestTooLargeError',message=>nil}},{mfa,{'Elixir.Plug.Adapters.Cowboy.Handler',init,3}},{stacktrace,[{'Elixir.Plug.Parsers',reduce,6,[{file,"lib/plug...

Is there a workaround to allow bigger files to be uploaded?

There seems to be a :length option keyword in Plug, but how could I set it from Phoenix? And what is the reason this particular value of 8_000_000 has been chosen?

Upvotes: 12

Views: 4745

Answers (3)

markquezada
markquezada

Reputation: 8535

Note that the accepted answer means that all request types will increase their maximum allowed lengths. As of Feb 2022, the Plug.Parsers docs show that you can set this just for the multipart parser in your endpoint.ex as:

If you want to increase the limit only for multipart requests (which is typically the ones used for file uploads), you can do:

plug Plug.Parsers,
     parsers: [
       :url_encoded,
       {:multipart, length: 20_000_000}, # Increase to 20MB max upload
       :json
     ]

Upvotes: 2

pmarreck
pmarreck

Reputation: 177

FYI, for the most up-to-date docs on this functionality (since this question and these answers are pretty out-of-date at this point), see the official docs at: https://phoenixframework.readme.io/docs/file-uploads

Upvotes: 1

Chris McCord
Chris McCord

Reputation: 8120

You can configure this in your config/config.exs file:

config :phoenix, MyApp.Router,
  ...
  parsers: [parsers: [:urlencoded, :multipart, :json],
            accept: ["*/*"],
            json_decoder: Poison,
            length: 100_000_000],

Upvotes: 6

Related Questions