Home / References / ESP32 Library / WebServer Library
Description
The setContentLength()
method in the ESP32 WebServer Library is used to specify the length of the content that will be sent in an HTTP response. By setting the content length explicitly, you inform the client (e.g., a web browser) about the exact size of the data to expect, which can improve performance and ensure proper handling of the response. This method is particularly useful when you know the size of the content in advance and want to optimize the communication process.
Please note that if the content length is not set correctly, or is set to the wrong value, the browser could have issues displaying the full web page. For example, if the specified content length is shorter than the actual data, the browser may truncate the response.
Attention: If the setContentLength()
method is not explicitly used in your code, the ESP32 WebServer Library will calculate the content length dynamically based on the data you send in the response. This automatic handling works well for most use cases, especially when the size of the content is not known in advance or when sending small amounts of data.
Syntax and Usage
The setContentLength()
method is called on a WebServer
object before sending the response with methods like send()
or sendContent()
. Below is the syntax and how to use it:
void setContentLength(const size_t contentLength);
This method has a single usage scenario:
- Setting the Content Length: Use this method to define the size of the content (in bytes) that will be sent to the client. It must be called before sending the response to ensure the HTTP header includes the correct
Content-Length
value. - 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.
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)
The setContentLength()
method requires one argument:
contentLength
: Asize_t
value representing the length of the content in bytes. This should match the total size of the data you plan to send in the HTTP response.
Return Value
The setContentLength()
method does not return a value (i.e., its return type is void
). It modifies the internal state of the WebServer
object to include the specified content length in the HTTP response header.
Example Codes
Basic Usage – Setting Content Length for Text Response
This code demonstrates how to use the ESP32 WebServer Library’s setContentLength()
method to explicitly set the content length of a text response. This is done by calculating the length of the string to be sent and then applying it before sending the response, ensuring the client knows the exact size of the incoming data.
To use this code, replace “your-SSID” and “your-PASSWORD” with your Wi-Fi credentials. After uploading the code to your ESP32, open the Serial Monitor to view the assigned IP address. Then, open a web browser and enter the IP address to see the “Hello from ESP32 Web Server!” message.
/*
* Author: Avant Maker
* Date: March 17, 2025
* Version: 1.0
* License: MIT
*
* Description:
* This example demonstrates how to use ESP32 WebServer Library's
* setContentLength() method to set the content length for a
* simple text response. The server calculates the length of
* the string to be sent and sets it as the content length
* before sending the response.
*
* 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>
const char* ssid = "your-SSID"; // Replace with your Wi-Fi SSID
const char* password = "your-PASSWORD"; // Replace with your Wi-Fi password
WebServer server(80);
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Define server routes
server.on("/", handleRoot);
// Start server
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
}
void handleRoot() {
String message = "Hello from AvantMaker.com ESP32 Web Server!";
// Set content length before sending the response
server.setContentLength(message.length());
// Set content type
server.send(200, "text/plain", message);
}
Advanced Usage – Setting Content Length for Binary Data
This code illustrates how to use the ESP32 WebServer Library’s setContentLength()
method when serving binary data, such as an image or file, in chunks. By setting the content length in advance, the server informs the client of the total size of the binary data, allowing for proper download handling. This example demonstrates sending a sample binary array in chunks, simulating a larger file transfer.
To use this code, replace “your-SSID” and “your-PASSWORD” with your Wi-Fi credentials. After uploading the code to your ESP32, open the Serial Monitor to find the assigned IP address. Then, open a web browser and enter the IP address. Click the provided link to download the binary data. The downloaded file, “sample.bin,” will contain the binary data sent from the ESP32. In a real application, you would replace the sample binary data with actual file or image data.
/*
* Author: Avant Maker
* Date: March 17, 2025
* Version: 1.0
* License: MIT
*
* Description:
* This example demonstrates how to use ESP32 WebServer Library's
* setContentLength() method when serving binary data.
*
* 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>
const char* ssid = "your-SSID"; // Replace with your Wi-Fi SSID
const char* password = "your-PASSWORD"; // Replace with your Wi-Fi password
WebServer server(80);
// Sample binary data (in a real scenario, this could be an image or file data)
const uint8_t sampleData[] = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, /* ... more bytes ... */};
const size_t dataSize = sizeof(sampleData);
void setup() {
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
// Define server routes
server.on("/binary", handleBinaryData);
server.on("/", handleRoot);
// Start server
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
}
void handleRoot() {
server.send(200, "text/html", "<html><body><h1>AvantMaker.com ESP32 Web Server</h1>"
"<p>Click <a href='/binary'>here</a> to download binary data</p></body></html>");
}
void handleBinaryData() {
// Set content type for binary data
server.sendHeader("Content-Disposition", "attachment; filename=sample.bin");
server.sendHeader("Content-Type", "application/octet-stream");
// Set the content length to inform client about the total size
server.setContentLength(dataSize);
// Send response code and headers (but not content yet)
server.send(200, "application/octet-stream", "");
// Send binary data in chunks
const size_t chunkSize = 256;
size_t sentBytes = 0;
while (sentBytes < dataSize) {
size_t currentChunkSize = min(chunkSize, dataSize - sentBytes);
server.client().write(&sampleData[sentBytes], currentChunkSize);
sentBytes += currentChunkSize;
}
}
ESP32 Library Index
- ESP32 WiFi Library
- ESP32 WiFiClient Library
- ESP32 HTTPClient Library
- ESP32 WiFiClientSecure Library
- ESP32 AsyncUDP Librarry
- ESP32 WebServer Library
- Server Operation
- Client Hnadling
- Routing and Handlers
- Authentication
- Request Information
- Request Header Management
- Response Information
- Server Configuration
- 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!