Anonymous - 2025-09-17

Originally posted by: aptonline

On further inspection I can see you are only serving specific files.

I'm wondering if something like this might be a better solution as it captures all files within the root and serves them.

#include <FS.h>
#include <SPIFFS.h>
#include <WebServer.h>

WebServer server(80);

void handleFileRequest() {
  String path = server.uri();
  if (path == "/") path = "/index.html";  // default

  if (SPIFFS.exists(path)) {
    File file = SPIFFS.open(path, "r");
    server.streamFile(file, getContentType(path));
    file.close();
    return;
  }
  server.send(404, "text/plain", "File Not Found");
}

void setup() {
  SPIFFS.begin(true);
  server.onNotFound(handleFileRequest);
  server.begin();
}

String getContentType(String filename) {
  if (filename.endsWith(".htm") || filename.endsWith(".html")) return "text/html";
  else if (filename.endsWith(".css")) return "text/css";
  else if (filename.endsWith(".js")) return "application/javascript";
  else if (filename.endsWith(".png")) return "image/png";
  else if (filename.endsWith(".jpg")) return "image/jpeg";
  else if (filename.endsWith(".ico")) return "image/x-icon";
  else if (filename.endsWith(".pdf")) return "application/pdf";
  return "text/plain";
}