Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Plug.Upload?

Tags:

elixir

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 ?

like image 515
salmane Avatar asked Apr 23 '19 13:04

salmane


Video Answer


1 Answers

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.

like image 145
Roman Boiko Avatar answered Oct 17 '22 19:10

Roman Boiko