handle_form.lua 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. -- Use a string builder pattern for performance reasons
  8. stringtab = {}
  9. bdata = ""
  10. repeat
  11. local add_data = mg.read()
  12. if add_data then
  13. stringtab[#stringtab+1] = add_data
  14. end
  15. until (add_data == nil);
  16. bdata = table.concat(stringtab)
  17. stringtab = nil
  18. -- Get the boundary string.
  19. bs = "--" .. ((mg.request_info.content_type):upper():match("BOUNDARY=(.*)"));
  20. -- The POST data has to start with the boundary string.
  21. -- Check this and remove the starting boundary.
  22. if bdata:sub(1, #bs) ~= bs then
  23. error "invalid format of POST data"
  24. end
  25. bdata = bdata:sub(#bs)
  26. -- The boundary now starts with CR LF.
  27. bs = "\r\n" .. bs
  28. -- Now loop through all the parts
  29. while #bdata>4 do
  30. -- Find the header of new part.
  31. part_header_end = bdata:find("\r\n\r\n", 1, true)
  32. -- Parse the header.
  33. local form_field_name, file_name
  34. h = bdata:sub(1, part_header_end+2)
  35. for key,val in h:gmatch("([^%:\r\n]*)%s*%:%s*([^\r\n]*)\r\n") do
  36. if key:upper() == "CONTENT-DISPOSITION" then
  37. form_field_name = val:match('name=%"([^%"]*)%"')
  38. file_name = val:match('filename=%"([^%"]*)%"')
  39. end
  40. end
  41. -- Remove the header from "bdata".
  42. bdata = bdata:sub(part_header_end+4)
  43. -- Find the end of the body by locating the boundary string.
  44. local part_body_end = bdata:find(bs, 1, true)
  45. -- Isolate the content, and drop it from "bdata".
  46. local form_field_value = bdata:sub(1,part_body_end-1)
  47. bdata = bdata:sub(part_body_end+#bs)
  48. -- Now the data (file content or field value) is isolated: We know form_field_name and form_field_value.
  49. -- Here the script should do something useful with the data. This example just sends it back to the client.
  50. if form_field_name then
  51. mg.write("Field name: " .. form_field_name .. "\r\n")
  52. end
  53. if file_name then
  54. mg.write("File name: " .. file_name .. "\r\n")
  55. end
  56. local len = #form_field_value
  57. if len<50 then
  58. mg.write("Field value: " .. form_field_value .. "\r\n")
  59. else
  60. mg.write("Field value: " .. form_field_value:sub(1, 40) .. " .. (" .. len .. " bytes)\r\n")
  61. end
  62. mg.write("\r\n")
  63. end