File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 11class 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)
You can’t perform that action at this time.
0 commit comments