How to Upload Files Using Post Controller

From ElixirBlocks
Jump to: navigation, search

Router

    live "/sandbox", SandboxLive, :home
    live "/sim-app", SimappLive, :home

Create a LiveView and render a form with the multipart attribute.


   <.form :let={f} action={~p"/transmit/#{switch}"} multipart>


                <.input
                  field={f[:switch_item]}
                  name="switch"
                  type="file"

                /> <input type="submit" />
     </.form>


Create a controller for the route /transmit/#{switch}


transmit_controller.ex

defmodule AppWeb.TransmitController do
  use AppWeb, :controller


  def home(conn, params) do

    IO.inspect params

    content = params["switch"].path

    IO.inspect"______________________________"

    case File.write("priv/my_file.json", content) do
      :ok ->
        IO.puts("File written successfully.")

      {:error, reason} ->
        IO.puts("Failed to write file: #{reason}")
    end

    redirect(conn, to: "/sim-app")
  end
end