ESP32 WebServer Library – onFileUpload()

Home / References / ESP32 Library / WebServer Library

Description

The onFileUpload() method in the ESP32 WebServer Library allows you to register a callback function that handles file uploads sent to your ESP32-based web server. This method is essential for projects requiring file transfer functionality, such as uploading configuration files, images, or other data to the ESP32’s filesystem. By defining a handler, you can process incoming file data efficiently, making it a powerful tool for interactive IoT applications.


Syntax and Usage

The onFileUpload() method is used to specify a function that will be called when a file upload is detected. Below is the basic syntax, followed by its usage variations:

server.onFileUpload(THandlerFunction ufn);

The method can be used in the following way:

  • Basic Usage with a Callback Function: Registers a single callback function to handle the entire file upload process, from start to finish.

Unlike some other WebServer methods, onFileUpload() does not offer multiple overloads or variations with additional arguments. It is designed to work with a single callback function that processes the upload using the server’s built-in HTTPUpload object.

For practical applications and examples of this method, please consult the “Example Code” section on this page. This section provides comprehensive guidance to help you better understand and apply the method effectively.


Argument(s)

  • ufn (THandlerFunction): A function of type THandlerFunction (a std::function) that you define to handle the file upload. This function is called repeatedly during the upload process, allowing you to manage the file data as it arrives. It has no parameters and returns no value, relying on the server’s upload() method to access upload details.

Return Value

The onFileUpload() method does not return a value. It simply registers the provided callback function with the WebServer instance. The actual handling of the upload process occurs within the callback function you define, where you can use the server’s upload() method to access upload status and data.


Example Codes

ESP32-WebFS: Simplifying SPIFFS File Management for Your ESP32 Projects

If you are looking for a tool or need guidance to upload and manage files in the SPIFFS (SPI Flash File System) of your ESP32 microcontroller, please check out our GitHub project, ESP32-WebFS , which simplifies SPIFFS file management for your ESP32 projects. It also serves as a great reference project that you can integrate into your own projects requiring ESP32 SPIFFS management.

ESP32-WebFS can turn your ESP32 microcontroller into a web server that provides a web-based interface to manage the SPIFFS on your ESP32. It enables you to upload, download, delete, and view files stored on your ESP32, making it easy to interact with your ESP32’s file system wirelessly.

For downloads and instructions on how to use this tool, please visit the ESP32-WebFS GitHub repository.

Below is an example demonstrating how to use the onFileUpload() method in a practical scenario. This corresponds to the basic usage described in Section 2.

Example: Handling File Uploads to SPIFFS

This example code demonstrates how to use the ESP32 WebServer library’s onFileUpload() method. This method enables the ESP32 to receive files uploaded through a web request and save them directly to the onboard SPIFFS (SPI Flash File System).

To use this code, first replace the placeholder values for ssid and password with your actual Wi-Fi network credentials. Then, compile and upload the sketch to your ESP32 board. Once running, the ESP32 will host a web server that listens for file uploads sent via an HTTP POST request to the /upload path.

/*
 * Author: Avant Maker
 * Date: April 4, 2025
 * Version: 1.0
 * License: MIT 
 * 
 * Description: 
 * This example demonstrates how to use ESP32 WebServer Library's 
 * onFileUpload() method to receive files uploaded through a web
 * request and save them directly to the onboard SPIFFS
 * (SPI Flash File System).
 *
 * Code Source:
 * This example code is sourced from the Comprehensive Guide
 * to the ESP32 Arduino Core Library, accessible on AvantMaker.com.
 * For additional code examples and in-depth documentation related to
 * the ESP32 Arduino Core Library, please visit:
 *
 * https://avantmaker.com/home/all-about-esp32-arduino-core-library/
 *
 * AvantMaker.com, your premier destination for all things
 * DIY, AI, IoT, Smart Home, and STEM projects. We are dedicated
 * to empowering makers, learners, and enthusiasts with
 * the resources they need to bring their innovative ideas to life.
 */

#include <WiFi.h>
#include <WebServer.h>
#include <SPIFFS.h>

const char* ssid = "your_SSID";          // Replace with your Wi-Fi SSID
const char* password = "your_PASSWORD";  // Replace with your Wi-Fi password3

WebServer server(80);
File fsUploadFile;

void handleFileUpload() {
    HTTPUpload& upload = server.upload();
    if (upload.status == UPLOAD_FILE_START) {
        String filename = upload.filename;
        if (!filename.startsWith("/")) {
            filename = "/" + filename;
        }
        Serial.println("Upload Started: " + filename);
        fsUploadFile = SPIFFS.open(filename, FILE_WRITE);
        if (!fsUploadFile) {
            Serial.println("Failed to open file for writing");
            return;
        }
    } else if (upload.status == UPLOAD_FILE_WRITE) {
        if (fsUploadFile) {
            fsUploadFile.write(upload.buf, upload.currentSize);
            Serial.printf("Uploaded %d bytes\n", upload.currentSize);
        }
    } else if (upload.status == UPLOAD_FILE_END) {
        if (fsUploadFile) {
            fsUploadFile.close();
            Serial.println("Upload Finished: " + String(upload.totalSize) + " bytes");
        }
    }
}

void setup() {
    Serial.begin(115200);
    if (!SPIFFS.begin(true)) {
        Serial.println("SPIFFS Mount Failed");
        return;
    }

    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }
    Serial.println("\nConnected to WiFi. IP: " + WiFi.localIP().toString());

    server.on("/upload", HTTP_POST, []() {
        server.send(200, "text/plain", "File Uploaded Successfully");
    });
    server.onFileUpload(handleFileUpload);
    server.begin();
    Serial.println("Server started");
}

void loop() {
    server.handleClient();
}
error: Content is protected !!