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).
Can someone gives an example ?
Plug.Upload
is not a plug, as Aleksei mentioned in comments. 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):
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 "/upload_photo", UploadController, :photo
Respective controller action will get a Plug.Upload
struct inside one of its parameters:
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
<%= 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With