handle_form_data.lua 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. mg.write("HTTP/1.0 200 OK\r\n")
  2. mg.write("Connection: close\r\n")
  3. mg.write("Content-Type: text/plain; charset=utf-8\r\n")
  4. mg.write("Cache-Control: max-age=0, must-revalidate\r\n")
  5. mg.write("\r\n")
  6. -- Read the entire body data (POST content) into "bdata" variable.
  7. bdata = ""
  8. repeat
  9. local add_data = mg.read()
  10. if add_data then
  11. bdata = bdata .. add_data
  12. end
  13. until (add_data == nil);
  14. -- Get the boundary string.
  15. bs = "--" .. ((mg.request_info.content_type):upper():match("BOUNDARY=(.*)"));
  16. -- The POST data has to start with the boundary string.
  17. -- Check this and remove the starting boundary.
  18. if bdata:sub(1, #bs) ~= bs then
  19. error "invalid format of POST data"
  20. end
  21. bdata = bdata:sub(#bs)
  22. -- The boundary now starts with CR LF.
  23. bs = "\r\n" .. bs
  24. -- Now loop through all the parts
  25. while #bdata>4 do
  26. -- Find the header of new part.
  27. part_header_end = bdata:find("\r\n\r\n", 1, true)
  28. -- Parse the header.
  29. h = bdata:sub(1, part_header_end+2)
  30. for key,val in h:gmatch("([^%:\r\n]*)%s*%:%s*([^\r\n]*)\r\n") do
  31. if key:upper() == "CONTENT-DISPOSITION" then
  32. form_field_name = val:match('name=%"([^%"]*)%"')
  33. file_name = val:match('filename=%"([^%"]*)%"')
  34. end
  35. end
  36. -- Remove the header from "bdata".
  37. bdata = bdata:sub(part_header_end+4)
  38. -- Find the end of the body by locating the boundary string.
  39. part_body_end = bdata:find(bs, 1, true)
  40. -- Isolate the content, and drop it from "bdata".
  41. form_field_value = bdata:sub(1,part_body_end-1)
  42. bdata = bdata:sub(part_body_end+#bs)
  43. -- Now the data (file content or field value) is isolated: We know form_field_name and form_field_value.
  44. -- Here the script should do something useful with the data. This example just sends it back to the client.
  45. mg.write("Field name: " .. form_field_name .. "\r\n")
  46. local len = #form_field_value
  47. if len<50 then
  48. mg.write("Field value: " .. form_field_value .. "\r\n")
  49. else
  50. mg.write("Field value: " .. form_field_value:sub(1, 40) .. " .. (" .. len .. " bytes)\r\n")
  51. end
  52. mg.write("\r\n")
  53. end