简体   繁体   English

如何将大文件从表单上传到 Phoenix?

[英]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.我有一个带有文件字段的 HTML 表单,用于将文件上传到我的 Phoenix 应用程序中的/file路由。

I mimic this behaviour from command line with curl -v -F "file=@MyTestFile" http://localhost:4000/file/ for faster testing.我使用curl -v -F "file=@MyTestFile" http://localhost:4000/file/从命令行模仿这种行为,以加快测试速度。

When I use a big file (turning point seems to be around 7.7MB), I get the following exception from Plug:当我使用大文件时(转折点似乎在 7.7MB 左右),我从 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... 18:40:38.897 [error] 进程 <0.420.0> 错误,退出值:{[{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,"库/插件...

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? Plug 中似乎有一个:length选项关键字,但我如何从 Phoenix 设置它? And what is the reason this particular value of 8_000_000 has been chosen?选择这个特定值8_000_000的原因是什么?

You can configure this in your config/config.exs file:您可以在config/config.exs文件中进行config/config.exs

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:截至 2022 年 2 月, Plug.Parsers文档显示您可以仅为endpoint.ex中的多部分解析器设置此项:

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
     ]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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