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
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.
-
What does
static
actually mean in this specific context?Mark– Mark2022年05月22日 08:53:39 +00:00Commented May 22, 2022 at 8:53 -
1In 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 eventschrisl– chrisl2022年05月22日 12:37:51 +00:00Commented May 22, 2022 at 12:37