Layer: L6 Presentation ยท Build flags: none (core; multipart is on by default)
What this example teaches
This parses a multipart/form-data POST body (RFC 7578) without allocation: protocore_multipart_parse() splits the in-buffer body into parts, and protocore_multipart_get_field() returns a named text field. A test form is served at /.
In-place, bounded parsing. The whole body must fit in BODY_BUF_SIZE (there is no streaming), so this is for small form fields and tiny uploads. The parser populates a Multipart struct that indexes into the existing body buffer rather than copying:
Multipart mp;
server.send(id, 400, "text/plain", "expected multipart/form-data (and within BODY_BUF_SIZE)");
return;
}
proto_bool protocore_multipart_parse(uint8_t *work, HttpReq *req, MultipartBody *mp)
Scan req's body as multipart/form-data, reading the boundary from.
const char * protocore_multipart_get_field(uint8_t *work, const MultipartBody *mp, const char *field)
The data pointer of the first part whose name matches field, or.
mp.part_count tells you how many parts were found. For large/streamed uploads straight to a file, see FileUpload.
The HTML form at / posts a name field and a file input so you can exercise it from a browser.
Build and run
pio ci --board=esp32dev --project-option="framework=arduino" \
--lib="." examples/L6-Presentation/Multipart/Multipart.ino
Flash, then browse to http://<ip>/ and submit the form.
Annotated source
The complete sketch (Multipart.ino), reproduced verbatim with added explanatory comments:
#include "protocore.h"
static const char *SSID = "YOUR_SSID";
static const char *PASSWORD = "YOUR_PASSWORD";
PC server;
static const char FORM[] = "<!doctype html><meta charset=utf-8><title>upload</title>"
"<form method=POST action=/upload enctype=multipart/form-data>"
"<input name=name placeholder=name> "
"<input type=file name=file> <button>upload</button></form>";
void handle_upload(uint8_t
id,
HttpReq *req)
{
Multipart mp;
{
server.send(id, 400, "text/plain", "expected multipart/form-data (and within BODY_BUF_SIZE)");
return;
}
char out[160];
snprintf(out, sizeof(out), "parsed %d part(s); field 'name' = %s", mp.part_count, name ? name : "(absent)");
server.send(id, 200, "text/plain", out);
}
void setup()
{
Serial.begin(115200);
Physical.wifi->init(SSID, PASSWORD);
Serial.print("Connecting to WiFi");
while (!Physical.wifi->ready())
{
delay(250);
Serial.print('.');
}
uint32_t ip = Physical.link->egress_ip();
Serial.printf("IP: %u.%u.%u.%u\n", (unsigned)(ip & 0xFF), (unsigned)((ip >> 8) & 0xFF),
(unsigned)((ip >> 16) & 0xFF), (unsigned)((ip >> 24) & 0xFF));
server.begin(80);
}
void loop()
{
server.handle();
}
@ HTTP_GET
Safe, idempotent read.
@ HTTP_POST
Non-idempotent create / action.
Layer 1 (Physical) - link bring-up, the interface registry, and live egress reporting.