-->
Page 1 of 1

Problem using Strings, more reliable ways to use?

PostPosted: Mon Oct 29, 2018 9:14 pm
by wanderer
I have an ESP8266 with the below code that I recently added an /ls endpoint for the ESPAsyncWebServer. It creates a String and iterates over any files in the root of the SPIFFS and is supposed to list them. For brevity, I left off the wifi/IP config, /update POST that handles the OTA flash, and the code that creates a file on the SPIFFS (these parts work fine) The issue I have is when I navigate to /ls on the ESP IP, I get this response:
SPIFFS
/datalog.txtt type='file' name='update'><input type='submit' value='Update'></form>


rather than something expected like this:
SPIFFS
/datalog.txt 1022


I've generally avoided using String types whenever possible and usually use char arrays but in this case I thought I'd try a String since I wasn't sure of the exact length, etc. Do I need to manually add a null terminator and this is just running into the next bit because it is missing? It doesn't have the two spaces between the file name and file size either though. Or is it allocating over top of the other const char array? Is there a better and/or more robust way to handle using Strings?

I'm not near the ESP at the moment to double check but I don't think it was using loads of memory or anything like that. I suppose I could move the htmlUpdate text out of RAM into PROGMEM to free up some as well; the current code was just a small page to make quick test iterations easier.

I reviewed the ESPAsyncWebServer and see I can print directly to the response which I'd believe would solve my issue in a different way but it would be nice to know if there's a better way to use Strings in case I need to in the future.

Code: Select all#include <Arduino.h>
#include <Streaming.h>
#include <ESP8266WiFi.h>
#include <FS.h>
#include <Hash.h>
#include <ESPAsyncTCP.h>
#include <ESPAsyncWebServer.h>

const char *htmlUpdate = "<form method='POST' action='/update' enctype='multipart/form-data'><input type='file' name='update'><input type='submit' value='Update'></form>";

AsyncWebServer server(80);

void setup()
{
    SPIFFS.begin();
    server.on("/ls", HTTP_GET, [](AsyncWebServerRequest *request) {
        String info = "SPIFFS";
        Dir dir = SPIFFS.openDir("/");
        while (dir.next()) {
            info += "\r\n" + dir.fileName();
            File f = dir.openFile("r");
            info += "  " + f.size();
        }
        request->send(200, "text/plain", info);
    });
    server.on("/update", HTTP_GET, [](AsyncWebServerRequest *request) {
        request->send(200, "text/html", htmlUpdate);
    });
    server.serveStatic("/", SPIFFS, "/");
    server.onNotFound([](AsyncWebServerRequest *request) {
        request->send(404, "text/plain", "File not found.");
    });
    server.begin();
}