Yield UploadFile in parse_multipart (#224)

This commit is contained in:
Serdar Dogruyol 2016-10-12 16:51:28 +03:00 committed by GitHub
parent 450dab9f81
commit 3342007701

View file

@ -79,19 +79,32 @@ def gzip(status : Bool = false)
add_handler HTTP::DeflateHandler.new if status add_handler HTTP::DeflateHandler.new if status
end end
# Parses a multipart/form-data request. This is really useful for file uploads. # nodoc:
struct UploadFile
getter field : String
getter data : IO::Delimited
getter meta : HTTP::FormData::FileMetadata
getter headers : HTTP::Headers
def initialize(@field, @data, @meta, @headers)
end
end
# Parses a multipart/form-data request. Yields an `UploadFile` object with `field`, `data`, `meta`, `headers` fields.
# Consider the example below taking two image uploads as image1, image2. To get the relevant data # Consider the example below taking two image uploads as image1, image2. To get the relevant data
# for each field you can use simple `if/switch` conditional. # for each file you can use simple `if/switch` conditionals.
# #
# post "/upload" do |env| # post "/upload" do |env|
# parse_multipart(env) do |field, data| # parse_multipart(env) do |f|
# image1 = data if field == "image1" # image1 = f.data if f.field == "image1"
# image2 = data if field == "image2" # image2 = f.data if f.field == "image2"
# puts f.meta
# puts f.headers
# "Upload complete" # "Upload complete"
# end # end
# end # end
def parse_multipart(env) def parse_multipart(env)
HTTP::FormData.parse(env.request) do |field, data| HTTP::FormData.parse(env.request) do |field, data, meta, headers|
yield field, data yield UploadFile.new field, data, meta, headers
end end
end end