[英]How to use Plug.Upload?
I would like to use Plug.Upload
in one of my routers without any library or framework on top but the official documentation here: https://hexdocs.pm/plug/Plug.Upload.html does not provide an example unlike for other plugs such as: Plug.Parsers
( https://hexdocs.pm/plug/Plug.Parsers.html ).我想在我的一个路由器中使用
Plug.Upload
,上面没有任何库或框架,但这里的官方文档: https ://hexdocs.pm/plug/Plug.Upload.html 没有提供与其他插件不同的示例例如: Plug.Parsers
( https://hexdocs.pm/plug/Plug.Parsers.html )。
Can someone gives an example?有人可以举个例子吗?
Plug.Upload
is not a plug, as Aleksei mentioned in comments. Plug.Upload
不是插件,正如 Aleksei 在评论中提到的那样。 You can't add it to your pipeline.您不能将其添加到管道中。 Instead,
:multipart
should be allowed in Plug.Parsers
configuration in your endpoint.ex
(it's there by default):相反,应该在
endpoint.ex
的Plug.Parsers
配置中允许:multipart
(默认情况下存在):
plug Plug.Parsers,
parsers: [:urlencoded, :multipart, :json],
pass: ["*/*"],
json_decoder: Phoenix.json_library()
You'll need a route for handling a POST request with the uploaded file:您需要一个路由来处理上传文件的 POST 请求:
post "/upload_photo", UploadController, :photo
Respective controller action will get a Plug.Upload
struct inside one of its parameters:相应的控制器操作将在其参数之一内获得一个
Plug.Upload
结构:
def photo(conn, %{"upload" => upload}) do
IO.inspect upload.photo, label: "Photo upload information"
# TODO: you can copy the uploaded file now,
# because it gets deleted after this request
json(conn, "Uploaded #{upload.photo.filename} to a temporary directory")
end
For testing, you can add a page that has a form with multipart: true
为了进行测试,您可以添加一个包含
multipart: true
表单的页面
<%= form_for @conn, "/upload_photo", [as: :upload, multipart: true], fn f -> %>
which has a file input其中有一个文件输入
<%= file_input f, :photo, class: "form-control" %>
Detailed instructions are provided in the Phoenix framework docs . Phoenix 框架文档中提供了详细说明。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.