简体   繁体   中英

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?

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],

仅供参考,有关此功能的最新文档(因为此问题和这些答案此时已过时),请参阅官方文档: https : //phoenixframework.readme.io/docs /文件上传

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
     ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM