1

I'm following the examples for ESP32:

  AsyncWebServer _server(80);

  _server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
  {
    request->send(SPIFFS, "/index.html", String(), false);
  });

  _server.on("/css/index.css", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/css/index.css", "text/css");
  });

  _server.onNotFound([](AsyncWebServerRequest *request){
    request->send(404);
  });

_server.begin();

With this approach I have to know in advance each file I store in the SPIFFS and add a handler for each one.

Is there a more elegant way to automatically serve any file that exists in the flash?

1 Answer 1

3

You can tell the webserver to serve the static content from a specific folder:

server.serveStatic("/", SPIFFS, "/").setDefaultFile("index.html");

In this case it serves on the root URL the content from the SPIFFS root. So if I place a file called image.jpg in the SPIFFS root it will be served at /image.jpg. For more information you can look at the corresponding section of the libraries Readme file.

2
  • What does static actually mean in this specific context?
    – Mark
    May 22 at 8:53
  • 1
    In this case it means files that are placed in SPIFFS (aka flash). These files can of course also be written and thus deliver a more dynamic content. But then you should mind the limited write cycles of flash memory. So its mainly meant for the static (not changing) files of your website, but can also be used to serve changing files. In one of my projects I use it to serve a log file of relatively rare events
    – chrisl
    May 22 at 12:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.