Arduino example: upload a file using ESPasyncWebServer.

Cellie
Posts: 8
Joined: Sat Feb 27, 2016 9:47 pm

Arduino example: upload a file using ESPasyncWebServer.

Postby Cellie » Thu Oct 12, 2017 8:07 pm

As I struggled with the sparse examples on the GitHub repo I spent some time making a simple example for uploading a file to ESPAsyncWebServer.

Files are uploaded through '/api/upload'.
I used curl to test this code with a command something like this:

Code: Select all

curl --user admin -F 'data=@LOCAL_FILENAME' 'ESP32_IP/api/upload'


The example:

Code: Select all

/****************************************************************************
 *
 *     Upload a file to esp32 with authorization
 *     
 *     Use curl to upload a file:
 *     
 *     curl --user admin:admin -F 'data=@FILENAME' 'ESP32_IP/api/upload'
 *     
 *****************************************************************************/
#include "FS.h"
#include "SD.h"
#include <AsyncTCP.h>
#include <ESPAsyncWebServer.h>

AsyncWebServer server(80);

const char* ssid = "-----";
const char* password = "-----";
const char* http_username = "admin";
const char* http_password = "admin";

void setup() {
  Serial.begin( 115200 );
 
  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.printf( "Connecting to SSID %s with PSK %s...\n", ssid, password  );
  if (WiFi.waitForConnectResult() != WL_CONNECTED) {
    Serial.printf("WiFi Failed!\n");
    return;
  }
  Serial.println( WiFi.localIP() );

  // upload a file to /upload
  server.on( "/api/upload", HTTP_POST, [](AsyncWebServerRequest *request){         
    request->send(200);
  }, [](AsyncWebServerRequest *request, String filename, size_t index, uint8_t *data, size_t len, bool final){       

    static bool  _authenticated;
    static size_t receivedBytes;
    static time_t startTimer;

    if( !index )
    {       
      _authenticated = false;
      if( request->authenticate(http_username, http_password) )
      {
        startTimer = millis();
        Serial.printf( "Starting upload. filename = %s\n", filename.c_str() );
        receivedBytes = 0;
        _authenticated = true;
        return;
      }
      else
      {
        //Serial.println( "Unauthorized acces." );
        return request->requestAuthentication();
      }
    } 
   
    if ( _authenticated  )
    {
      receivedBytes += len;
      //Serial.printf( "received %i bytes\n",receivedBytes );
    }
   
    if ( final && _authenticated )
    {
      Serial.println( "Upload done." );
      Serial.printf( "Got %i bytes in %i ms.\n\n", receivedBytes, millis() - startTimer );
    }
  });
  server.onNotFound([](AsyncWebServerRequest *request){
    request->send(404, "text/plain", "Not found.");
  });

  server.begin(); 

  Serial.println( "Ready for upload" );
}

void loop() {
  // put your main code here, to run repeatedly:

}

Who is online

Users browsing this forum: No registered users and 2 guests