httpserver-static.lua 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. -- httpserver-static.lua
  2. -- Part of nodemcu-httpserver, handles sending static files to client.
  3. -- Author: Marcos Kirsch
  4. local function getMimeType(ext)
  5. -- A few MIME types. Keep list short. If you need something that is missing, let's add it.
  6. local mt = {css = "text/css", gif = "image/gif", html = "text/html", ico = "image/x-icon", jpeg = "image/jpeg", jpg = "image/jpeg", js = "application/javascript", josn="application/json", png = "image/png"}
  7. if mt[ext] then return mt[ext] else return "text/plain" end
  8. end
  9. local function sendHeader(connection, code, codeString, mimeType)
  10. connection:send("HTTP/1.0 " .. code .. " " .. codeString .. "\r\nServer: nodemcu-httpserver\r\nContent-Type: " .. mimeType .. "\r\nConnection: close\r\n\r\n")
  11. end
  12. return function (connection, args)
  13. sendHeader(connection, 200, "OK", getMimeType(args.ext))
  14. --print("Begin sending:", args.file)
  15. -- Send file in little chunks
  16. local continue = true
  17. local bytesSent = 0
  18. while continue do
  19. -- NodeMCU file API lets you open 1 file at a time.
  20. -- So we need to open, seek, close each time in order
  21. -- to support multiple simultaneous clients.
  22. file.open(args.file)
  23. file.seek("set", bytesSent)
  24. local chunk = file.read(512)
  25. file.close()
  26. if chunk == nil then
  27. continue = false
  28. else
  29. coroutine.yield()
  30. connection:send(chunk)
  31. bytesSent = bytesSent + #chunk
  32. --print("Sent" .. args.file, bytesSent)
  33. end
  34. end
  35. --print("Finished sending:", args.file)
  36. end