Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 409
adanselm Avatar asked Nov 25 '14 18:11

adanselm


3 Answers

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
     ]
like image 197
markquezada Avatar answered Oct 02 '22 22:10

markquezada


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

like image 25
pmarreck Avatar answered Oct 02 '22 21:10

pmarreck


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],
like image 38
Chris McCord Avatar answered Oct 02 '22 22:10

Chris McCord