简体   繁体   中英

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 ).

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 .

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