Skip to content

Commit 1cc2b99

Browse files
committed
Use IO.pipe replace IO::Memory for less memory usage.
1 parent 164adc0 commit 1cc2b99

1 file changed

Lines changed: 15 additions & 8 deletions

File tree

src/actions/api/upload.cr

Lines changed: 15 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,29 @@
11
class Api::Upload < ApiAction
22
post "/api/upload" do
33
source = params.from_multipart.last["source"]
4-
io = IO::Memory.new
4+
5+
# use IO.pipe instead of IO::Memory to reduce memory usage.
6+
# https://forum.crystal-lang.org/t/upload-image-failed-use-http-client-but-test-with-postman-work/8171/13
7+
8+
reader, writer = IO.pipe
59
headers = HTTP::Headers.new
6-
form_data = HTTP::FormData::Builder.new(io)
10+
form_data = HTTP::FormData::Builder.new(writer)
711
headers["Content-Type"] = form_data.content_type
812

9-
file = File.open(source.path) do |file|
10-
form_data.field("key", FREEIMAGE_HOST_API_KEY)
11-
form_data.file("source", file, HTTP::FormData::FileMetadata.new(filename: source.filename))
12-
form_data.finish
13+
spawn do
14+
file = File.open(source.path) do |file|
15+
form_data.field("key", FREEIMAGE_HOST_API_KEY)
16+
form_data.file("source", file, HTTP::FormData::FileMetadata.new(filename: source.filename))
17+
form_data.finish
18+
end
19+
ensure
20+
writer.close
1321
end
1422

15-
p! headers
1623
response = HTTP::Client.post(
1724
url: "https://freeimage.host/api/1/upload",
1825
headers: headers,
19-
body: io.rewind
26+
body: reader
2027
)
2128

2229
body = JSON.parse(response.body)

0 commit comments

Comments
 (0)