httpserver-static.lua 1.2 KB

12345678910111213141516171819202122232425262728293031323334
  1. -- httpserver-static.lua
  2. -- Part of nodemcu-httpserver, handles sending static files to client.
  3. -- Author: Marcos Kirsch
  4. return function (connection, req, args)
  5. --print("Begin sending:", args.file)
  6. --print("node.heap(): ", node.heap())
  7. dofile("httpserver-header.lc")(connection, 200, args.ext, args.isGzipped)
  8. -- Send file in little chunks
  9. local continue = true
  10. local size = file.list()[args.file]
  11. local bytesSent = 0
  12. -- Chunks larger than 1024 don't work.
  13. -- https://github.com/nodemcu/nodemcu-firmware/issues/1075
  14. local chunkSize = 1024
  15. while continue do
  16. collectgarbage()
  17. -- NodeMCU file API lets you open 1 file at a time.
  18. -- So we need to open, seek, close each time in order
  19. -- to support multiple simultaneous clients.
  20. file.open(args.file)
  21. file.seek("set", bytesSent)
  22. local chunk = file.read(chunkSize)
  23. file.close()
  24. connection:send(chunk)
  25. bytesSent = bytesSent + #chunk
  26. chunk = nil
  27. --print("Sent: " .. bytesSent .. " of " .. size)
  28. if bytesSent == size then continue = false end
  29. end
  30. --print("Finished sending: ", args.file)
  31. end