Skip to content

Commit 2a3aeeb

Browse files
committed
Add cleanup methods for file uploads and temporary files
1 parent 4352774 commit 2a3aeeb

File tree

3 files changed

+27
-8
lines changed

3 files changed

+27
-8
lines changed

src/kemal/file_upload.cr

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,5 +20,10 @@ module Kemal
2020
@read_time = upload.read_time
2121
@size = upload.size
2222
end
23+
24+
def cleanup
25+
@tempfile.close
26+
::File.delete(@tempfile.path) if ::File.exists?(@tempfile.path)
27+
end
2328
end
2429
end

src/kemal/param_parser.cr

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,15 @@ module Kemal
2424
@files_parsed = false
2525
end
2626

27+
def cleanup_temporary_files
28+
return if @files.empty? && @all_files.empty?
29+
30+
@files.each_value &.cleanup
31+
@all_files.each_value do |file_uploads|
32+
file_uploads.each &.cleanup
33+
end
34+
end
35+
2736
private def unescape_url_param(value : String)
2837
value.empty? ? value : URI.decode(value)
2938
rescue

src/kemal/route_handler.cr

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -47,16 +47,21 @@ module Kemal
4747

4848
# Processes the route if it's a match. Otherwise renders 404.
4949
private def process_request(context)
50-
raise Kemal::Exceptions::RouteNotFound.new(context) unless context.route_found?
51-
return if context.response.closed?
52-
content = context.route.handler.call(context)
50+
begin
51+
raise Kemal::Exceptions::RouteNotFound.new(context) unless context.route_found?
52+
return if context.response.closed?
53+
content = context.route.handler.call(context)
5354

54-
if !Kemal.config.error_handlers.empty? && Kemal.config.error_handlers.has_key?(context.response.status_code)
55-
raise Kemal::Exceptions::CustomException.new(context)
56-
end
55+
if !Kemal.config.error_handlers.empty? && Kemal.config.error_handlers.has_key?(context.response.status_code)
56+
raise Kemal::Exceptions::CustomException.new(context)
57+
end
58+
59+
context.response.print(content)
5760

58-
context.response.print(content)
59-
context
61+
context
62+
ensure
63+
context.params.cleanup_temporary_files
64+
end
6065
end
6166

6267
private def radix_path(method, path)

0 commit comments

Comments
 (0)