Skip to content

Commit bc7e0e5

Browse files
committed
Implement deleting an uploaded file
If we want to clean memory within a very long-lived process, we currently have no way to do so. This attempts to offer a way to delete a file earlier when we know it won't be needed anymore but it's process owner will.
1 parent df49f29 commit bc7e0e5

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

lib/plug/upload.ex

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

62+
@doc """
63+
Deletes the given upload file.
64+
"""
65+
@spec delete(t | binary) :: :ok | {:error, term}
66+
def delete(%__MODULE__{path: path}), do: delete(path)
67+
68+
def delete(path) when is_binary(path) do
69+
with :ok <- :file.delete(path, [:raw]) do
70+
:ets.delete_object(@path_table, {self(), path})
71+
:ok
72+
end
73+
end
74+
6275
@doc """
6376
Assign ownership of the given upload file to another process.
6477

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)