Example sketches for the new Arduino IDE for ESP8266

Moderator: igrr

User avatar
By mvdbro
#30248
martinayotte wrote:Good !
Maybe a small change still need to be done, but not urgent : is the ContentLength received by the browser in the header is actually a '0' or the real size ?

I checked and the actual size (that has been set with WebServer.setContentLength(size)) is send to the browser.
So I think no changes needed.
User avatar
By danbicks
#57117
mvdbro wrote:I figured out that it is still possible to send data after WebServer.Send(). It seems that the client connection will not be closed until the handler function terminates.

This works in my sketch:

Code: Select all  WiFiClient client = WebServer.client();
  WebServer.setContentLength(2048);
  WebServer.sendHeader("Content-Disposition", "attachment; filename=config.txt");
  WebServer.send(200, "application/octet-stream", "");
  client.write((const char*)data, 2048);


So it seems that no changes are actually needed.


Hi mvdbro,

Do you have a working example of this pulling down a Spiffs file from an ESP through a web browser request. This is really cool.

Cheers

Dans
User avatar
By martinayotte
#57118 If it is plain text file, here some code. If other content types are needed, the header will need to change accordingly.

Code: Select allvoid handleViewFile() {
  String filename = String("");
  if (webserver.hasArg("file")) {
    filename = webserver.arg("file");
  }
  String str = String("Sending File '");
  str += filename + "' to " + webserver.client().remoteIP().toString() + "\r\n\r\n";
  Serial.println(str);
  if (!SPIFFS.begin()) {
    Serial.println("SPIFFS failed to mount !\r\n");
  }
  File f = SPIFFS.open(filename.c_str(), "r");
  if (!f) {
    String str = "Can't open '" + filename + "' !\r\n";
    Serial.println(str);
  }
  else {
    char buf[1024];
    int siz = f.size();
    webserver.setContentLength(str.length() + siz);
    webserver.send(200, "text/plain", str);
    while(siz > 0) {
      size_t len = std::min((int)(sizeof(buf) - 1), siz);
      f.read((uint8_t *)buf, len);
      webserver.client().write((const char*)buf, len);
      siz -= len;
    }
    f.close();
  }