diff --git a/lib/plug/upload.ex b/lib/plug/upload.ex index 53a4697a..42e9b035 100644 --- a/lib/plug/upload.ex +++ b/lib/plug/upload.ex @@ -59,6 +59,22 @@ defmodule Plug.Upload do end end + @doc """ + Deletes the given upload file. + + Uploads are automatically removed when the current process terminates, + but you may invoke this to request the file to be removed sooner. + """ + @spec delete(t | binary) :: :ok | {:error, term} + def delete(%__MODULE__{path: path}), do: delete(path) + + def delete(path) when is_binary(path) do + with :ok <- :file.delete(path, [:raw]) do + :ets.delete_object(@path_table, {self(), path}) + :ok + end + end + @doc """ Assign ownership of the given upload file to another process. diff --git a/test/plug/upload_test.exs b/test/plug/upload_test.exs index 89a218b9..432c7903 100644 --- a/test/plug/upload_test.exs +++ b/test/plug/upload_test.exs @@ -24,6 +24,13 @@ defmodule Plug.UploadTest do end end + test "removes the random file on request" do + {:ok, path} = Plug.Upload.random_file("sample") + File.open!(path) + :ok = Plug.Upload.delete(path) + wait_until(fn -> not File.exists?(path) end) + end + defp wait_until(fun) do if fun.() do :ok