prampec / IotWebConf

ESP8266/ESP32 non-blocking WiFi/AP web configuration Arduino library
MIT License
528 stars 141 forks source link

how to serve file from SPIFFS? #214

Open societyofrobots opened 3 years ago

societyofrobots commented 3 years ago

I'd like to serve some txt files stored in SPIFFS.

The one part I can't figure out is in setup(). This is the equivalent for Async, but not sure how to do it with IotWebConf:

server.on("/logs", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/log0.txt", "text/html");
});
societyofrobots commented 3 years ago

I couldn't figure out the easy way to do it, so I did it the hard way.

This function loads the file into a string:

void serve_logs()
  {
  String s = F("<!DOCTYPE html><html lang=\"en\"><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, user-scalable=no\"/>");

  s += "<title>";
  s += iotWebConf.getThingName();
  s += "</title><body>";

  File file = SPIFFS.open("/log0.txt", "r");

  if(!file || file.isDirectory()){
    Serial.println("- failed to open file for reading");
    s += "no logs available</body></html>\n";    
    server.send(200, "text/html", s);
    return;
    }

  String a;
  while(file.available())
    {
    a = char(file.read());
    if(a=="\n")
      s+="<br>";
    else
      s += a;
    }    

  file.close();

  s += "</body></html>\n";

  server.send(200, "text/html", s);
  }

And this goes in setup() server.on("/logs", serve_logs);

micbuh commented 3 years ago

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

societyofrobots commented 3 years ago

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

Where/how would I call this line?

For example, I'd want someone to click a link to a .txt and it'd just load up. Or ideally long press the link, and the user would have the option to save the file.