Skip to content

Instantly share code, notes, and snippets.

@zot24
Created November 10, 2015 10:25
Show Gist options
  • Save zot24/03e97fe48e74c4cb84a9 to your computer and use it in GitHub Desktop.
Save zot24/03e97fe48e74c4cb84a9 to your computer and use it in GitHub Desktop.
Multipart Parser for Lua based on Mashape (Multipart Parser for Lua)
local function loadFormInput ()
local result = {
data = {},
indexes = {}
}
-- Should be set to 4096 or 8192 for real-world settings
local chunk_size = 4096
local form, err = upload:new(chunk_size)
if not form then
-- There is no form data to read from
return nil
end
form:set_timeout(1000) -- 1 sec
local part_index = 1
local part_name, part_value
while true do
local typ, res, err = form:read()
if not typ then
return nil -- An error happened, 'failed to read'
end
if typ == "header" then
if stringy.startswith(string.lower(res[1]), "content-disposition") then
local parts = stringy.split(res[3], ";")
local current_parts = stringy.split(stringy.strip(parts[2]), "=")
if string.lower(table.remove(current_parts, 1)) == "name" then
local current_value = stringy.strip(table.remove(current_parts, 1))
part_name = string.sub(current_value, 2, string.len(current_value) - 1)
end
end
elseif typ == "body" then
part_value = res
elseif typ == "part_end" then
if part_name ~= nil then
result.data[part_index] = {
name = part_name,
value = part_value
}
result.indexes[part_name] = part_index
-- Reset fields for the next part
part_value = nil
part_name = nil
part_index = part_index + 1
end
elseif typ == "eof" then
-- finish reading the input
break
else
-- do nothing
end
end
return result
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment