Skip to content

Commit 44b54b7

Browse files
authored
Implement deleting an uploaded file (#1289)
1 parent df49f29 commit 44b54b7

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

lib/plug/upload.ex

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,22 @@ defmodule Plug.Upload do
5959
end
6060
end
6161

62+
@doc """
63+
Deletes the given upload file.
64+
65+
Uploads are automatically removed when the current process terminates,
66+
but you may invoke this to request the file to be removed sooner.
67+
"""
68+
@spec delete(t | binary) :: :ok | {:error, term}
69+
def delete(%__MODULE__{path: path}), do: delete(path)
70+
71+
def delete(path) when is_binary(path) do
72+
with :ok <- :file.delete(path, [:raw]) do
73+
:ets.delete_object(@path_table, {self(), path})
74+
:ok
75+
end
76+
end
77+
6278
@doc """
6379
Assign ownership of the given upload file to another process.
6480

test/plug/upload_test.exs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,13 @@ defmodule Plug.UploadTest do
2424
end
2525
end
2626

27+
test "removes the random file on request" do
28+
{:ok, path} = Plug.Upload.random_file("sample")
29+
File.open!(path)
30+
:ok = Plug.Upload.delete(path)
31+
wait_until(fn -> not File.exists?(path) end)
32+
end
33+
2734
defp wait_until(fun) do
2835
if fun.() do
2936
:ok

0 commit comments

Comments
 (0)