Home / References / ESP32 Library / WebServer Library
Description
The clientContentLength()
method is a member function of the ESP32 WebServer
class. It returns the value specified in the Content-Length
HTTP header of the incoming client request. This header tells the server the size, in bytes, of the request body that follows the headers. It’s particularly relevant for handling HTTP methods like POST or PUT, where clients send data (the request body) to the server.
Knowing the content length can be useful for validating requests (e.g., checking if the size exceeds a limit) or for preparing to read the request body data.
Syntax and Usage
The clientContentLength()
method is called on an instance of the WebServer
object, typically from within a request handler function, especially one designed to process request bodies.
server.clientContentLength()
This is the standard way to use the method. It takes no arguments and returns the size of the request body as reported by the client.// Assuming 'server' is your WebServer object instance // Inside a request handler function: size_t len = server.clientContentLength(); // Corrected method name if (len > 0) { Serial.print("Client declared content length: "); Serial.println(len); // Potentially use 'len' to check size limits or prepare a buffer } else { Serial.println("No Content-Length header or length is zero."); }
This syntax is used inside handler functions registered using methods likeserver.on()
. It’s often checked before attempting to read or process the request body content.
Argument(s)
This method does not require any arguments.
Return Value
The clientContentLength()
method returns a size_t
value, which is an unsigned integer type representing the size of the request body in bytes, as indicated by the Content-Length
header in the client’s request.
If the Content-Length
header is not present in the request, or if its value is explicitly “0”, this method will return 0
.
Important: This method returns the length declared by the client in the header. While the library typically ensures the full body is received before calling the handler for simple cases, this value is primarily an indication of expected size based on the header.
Example Codes
Handling POST Data and Reporting Content Length
This example, based on the code you provided, sets up a server with a handler for the path /data
. If a GET request is made to /data
, it serves a simple HTML form. When this form is submitted, it sends a POST request back to /data
. The handler then checks if the method is POST, retrieves the declared content length using server.clientContentLength()
, reads the POST body content using server.arg("plain")
, and sends a response back to the client confirming the received length and data.
To test this: Upload the code, connect the ESP32 to WiFi, and navigate to http://<YourESP32IP>/data
in your browser. Fill in the form and submit it. The resulting page will show the content length reported by the browser (via the `clientContentLength()` method) and the data you submitted.
/*
* Author: Avant Maker
* Date: April 15, 2025
* Version: 1.0
* License: MIT
*
* Description:
* This example demonstrates how to use ESP32 WebServer Library's
* clientContentLength() method to get the "Content-Length" value from the
* client’s HTTP request.
*
* 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>
// Replace with your network credentials
const char* ssid = "your_SSID"; // Replace with your Wi-Fi SSID
const char* password = "your_PASSWORD"; // Replace with your Wi-Fi password
// Create a WebServer object on port 80
WebServer server(80);
// HTML for the data submission form (served on GET request)
const char* HTML_FORM = R"rawliteral(
<!DOCTYPE html>
<html>
<head><title>ESP32 POST Example</title></head>
<body>
<h1>Submit Data via POST</h1>
<form action="/data" method="post">
<label for="data">Enter Data:</label><br>
<input type="text" id="data" name="plain" size="50"><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
)rawliteral";
// Function to handle requests to /data path
void handleData() {
if (server.method() == HTTP_GET) {
// Serve the HTML form for GET requests
server.send(200, "text/html", HTML_FORM);
} else if (server.method() == HTTP_POST) {
// Handle POST requests
String message = "POST request received.\n";
// Get the declared content length
size_t declaredLength = server.clientContentLength();
message += "Declared Content-Length: ";
message += String(declaredLength);
message += " bytes\n";
Serial.print("Declared Content-Length: ");
Serial.println(declaredLength);
// Check if there is body content based on args (library parses it)
if (server.hasArg("plain") == false) {
message += "No 'plain' argument found (POST body might be empty or incorrect format).\n";
} else {
String postBody = server.arg("plain");
message += "Received Body Content:\n";
message += postBody;
message += "\n";
message += "Actual received body length (from arg): ";
message += String(postBody.length()); // Length of the actual received string
message += " bytes\n";
Serial.println("Received POST body:");
Serial.println(postBody);
}
// Send the response back to the client
server.send(200, "text/plain", message);
} else {
// Handle other methods (optional)
server.send(405, "text/plain", "Method Not Allowed");
}
}
void setup() {
Serial.begin(115200);
delay(100);
// Connect to Wi-Fi
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected.");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.println("Navigate to http://" + WiFi.localIP().toString() + "/data to submit data.");
// Register the handler function for the /data path
server.on("/data", handleData);
// Optional: Add a root handler or not found handler
server.on("/", HTTP_GET, [](){
server.send(200, "text/html", "<html><body><h1>AvantMaker ESP32 Web Server</h1><p>Go to <a href='/data'>/data</a> to test POST.</p></body></html>");
});
server.onNotFound([](){
server.send(404, "text/plain", "Not Found");
});
// Start the server
server.begin();
Serial.println("HTTP server started");
}
void loop() {
// Handle incoming client requests
server.handleClient();
}
Note: The form uses the name “plain” for the input field. The ESP32 WebServer library convention is to make the entire raw POST body available via `server.arg(“plain”)` when the `Content-Type` is not `application/x-www-form-urlencoded` or `multipart/form-data`. Standard HTML forms often default to `application/x-www-form-urlencoded`, in which case the data would be accessed via `server.arg(“input_field_name”)`. The example uses `name=”plain”` to simplify accessing the raw body via `server.arg(“plain”)`, though this isn’t standard HTML practice but works with this library’s feature.
ESP32 Library Index
- ESP32 WiFi Library
- ESP32 WiFiClient Library
- ESP32 HTTPClient Library
- ESP32 WiFiClientSecure Library
- ESP32 WebServer Library
- Server Operation
- Client Hnadling
- Routing and Handlers
- Authentication
- Request Information
- Which ESP32 Boards are Recommended for Learners
- How to Copy Codes from AvantMaker.com
- What is SPIFFS and how to upload files to it?
- What is LIttleFS and how to upload files to it?
Ready to experiment and explore more about ESP32? Visit our website’s All About ESP32 Resources Hub, packed with tutorials, guides, and tools to inspire your maker journey. Experiment, explore, and elevate your skills with everything you need to master this powerful microcontroller platform!