1
votes

I have the following code:

def show(conn) do
  conn
  |> put_resp_header("content-disposition", ~s(attachment; filename="tmp.png"))
  |> Plug.Conn.send_file(200, "tmp.png")
end

I'm trying to delete the tmp.png file after sending it, however if I do

def show(conn) do
  conn
  |> put_resp_header("content-disposition", ~s(attachment; filename="tmp.png"))
  |> Plug.Conn.send_file(200, "tmp.png")

  File.rm("tmp.png")
end

I'm predictabely told I must return a connection from the controller.

Is there any way of me removing the file after the file is sent?

Thanks in advance

1

1 Answers

2
votes

You have to return conn from show/1, so this would probably work

def show(conn) do
  conn =
    conn
    |> put_resp_header("content-disposition", ~s(attachment; filename="tmp.png"))
    |> Plug.Conn.send_file(200, "tmp.png")

  File.rm("tmp.png")
  halt(conn)
end

Another, most probably reliable way to do it, would be to spawn a separate process to remove a file.

defp send_and_remove_file(conn, file) do
  conn = Plug.Conn.send_file(conn, 200, "tmp.png")
  spawn(File, :rm, [file])
  halt(conn)
end

def show(conn) do
  conn
  |> put_resp_header("content-disposition", ~s(attachment; filename="tmp.png"))
  |> send_and_remove_file("tmp.png")
end