Your new topic does not fit any of the above??? Check first. Then post here. Thanks.

Moderator: igrr

User avatar
By robotmaker42
#32149 I mashed the web update example, the FSwebBrowser example, and some code I wrote myself. when a file is downloaded to the esp8266( has to be some form of text EX: .txt , .html) it prints it to serial

here it is:

Code: Select all#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <FS.h>

const char* ssid = "xxxxxxxxxx";
const char* password = "xxxxxxxx";
String filename;
ESP8266WebServer server(80);
//holds the current upload
File UploadFile;

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







void setup() {
  SPIFFS.begin();
  Serial.begin(115200);
  Serial.println();
  Serial.println("Booting Sketch...");
  WiFi.mode(WIFI_AP_STA);
  WiFi.begin(ssid, password);

  if (WiFi.waitForConnectResult() == WL_CONNECTED) {

    server.on("/", HTTP_GET, []() {
      server.sendHeader("Connection", "close");
      server.sendHeader("Access-Control-Allow-Origin", "*");
      server.send(200, "text/html", serverIndex);
    });

    server.onFileUpload([]() {
      if (server.uri() != "/update") return;
      HTTPUpload& upload = server.upload();
      if (upload.status == UPLOAD_FILE_START) {
        filename = upload.filename;
        Serial.print("Upload Name: "); Serial.println(filename);
        UploadFile = SPIFFS.open("/data/" + filename, "w");
      } else if (upload.status == UPLOAD_FILE_WRITE) {
        if (UploadFile)
          UploadFile.write(upload.buf, upload.currentSize);
      } else if (upload.status == UPLOAD_FILE_END) {
        if (UploadFile)
          UploadFile.close();
          FileRead();  // After file downloads, read it
      }

    });



    server.on("/update", HTTP_POST, []() {
      server.sendHeader("Connection", "close");
      server.sendHeader("Access-Control-Allow-Origin", "*");
      server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
      ESP.restart();
    });
    server.begin();
    Serial.println(WiFi.localIP());
  } else {
    Serial.println("WiFi Failed");
  }
}



void loop() {
  server.handleClient();
  delay(1);
}




void FileRead() {
  String NewLine;
  Serial.println("reading...");
  Serial.println("/data/" + filename);


  if (SPIFFS.exists("/data/" + filename)) {
    File FileRead = SPIFFS.open("/data/" + filename, "r");
    Serial.print("output: ");
    Serial.println();
    while (FileRead.available() > 0) {
      char In = FileRead.read();
      NewLine += In;

      if (In == '\n') {
        Serial.print(NewLine);
        NewLine = "";
      }
    }

    FileRead.close();
  }
}

User avatar
By ElGalloGringo
#32155 Here is the code that I am using and tested this morning. You can see that it has two parts. The first in the handler for when the upload actually happens. The second is the handler for when someone hits the update URL. I am using a python script to upload all my HTML, CSS, JS, PNG files to the SPIFFS partition on the device so I don't have to burn the whole thing every time. I put this in the setup() function after I know the Wifi is initialized and connected to and access point (or is running as an access point). My full examples are at https://github.com/jpswensen/ESP8266_WebGen under the AdvancedWebServerHuzzah_SPIFFS sketch.

Code: Select all// Upload new HTML files
  // This responds to commands like:
  //    curl -F "file=@css/dropdown.css;filename=/css/dropdown.css" 192.168.4.1/update
  //    curl -F "file=@index.html;filename=/index.html" 192.168.4.1/update
  // To upload web pages. This is using the underlying SPIFF filesystem, but doesn't require
  // a completely new upload
  server.onFileUpload([](){
     
      if(server.uri() != "/update") return;
      HTTPUpload& upload = server.upload();
      if(upload.status == UPLOAD_FILE_START){
        Serial.setDebugOutput(true);
        WiFiUDP::stopAll();
        Serial.printf("Update: %s\n", upload.filename.c_str());

        //  (1) Rename the old file
        if (SPIFFS.exists(upload.filename.c_str()))
        {
          SPIFFS.rename(upload.filename.c_str(),(upload.filename+".BAK").c_str());
        }
        //  (2) Create the new file
        f = SPIFFS.open(upload.filename.c_str(), "w+");
        uploadError = "";
       
      } else if(upload.status == UPLOAD_FILE_WRITE){
        // (1) Append this buffer to the end of the open file
        if (f.write(upload.buf, upload.currentSize) != upload.currentSize){
          uploadError = "Error writing file chunk";
        }
        else
        {
          Serial.printf("Wrote bytes: %d\n", upload.currentSize);
        }
       
      } else if(upload.status == UPLOAD_FILE_END){

      // Close the file
        f.close();
        // (1) Check if the update was successful
        // (2) If Successful, close the file and delete the renamed one
        // (3) If failed, close and delete the new file and move the renamed one back in place
        if (uploadError == "")
        {
          Serial.printf("Upload error: %s\n", uploadError.c_str());
          SPIFFS.remove((upload.filename+".BAK").c_str());
        }
        else
        {
          Serial.printf("Error uploading new file putting old file back in place: %s\n", upload.filename.c_str());
          SPIFFS.remove((upload.filename).c_str());
          SPIFFS.rename((upload.filename+".BAK").c_str(), upload.filename.c_str());
        }
       
        Serial.setDebugOutput(false);
      }
      yield();
    });
    server.on("/update", HTTP_POST, [](){
      server.sendHeader("Connection", "close");
      server.sendHeader("Access-Control-Allow-Origin", "*");

      // TODO: Send back better information based on whether the upload was successful.
      server.send(200, "text/plain", uploadError);
     
      //ESP.restart(); // I don't think we need to restart after every file upload
     
    });