Good examples of the Arduino ESP8266Webserver are difficult to find when it comes to writing a HTTP server which accepts POST.
There are different ways a POST request can commonly be made:
- Using a form
- Performing a simple fetch in Javascript
- Performing a multipart fetch in Javascript
And there are different ways the server should respond depending on how the submission is made.
The Request
Using a form
<form action="/upload?o=option" method="POST" enctype="multipart/form-data"><p>File: <input type="file" name="name"></p><input type="submit" value="Upload"></form>
Performing a multipart Fetch in Javascript
// Prepare binary and text dataconst binarydata = new Uint8Array(new ArrayBuffer(1024)) ;
const textdata = "textmessage" ;
compressText(textdata, binarydata) ;
// Create formData object
const formData = new FormData() ;
// Store binary data
const b_blob = new Blob([binarydata], { type: "application/octet-stream"}) ;
formData.append("binarylabel", b_blob, "binary.dat") ;
// Store text data
const t_blob = new Blob([textdata], { type: "text/plain" }) ;
formData.append("textlabel", t_blob, "text.txt") ;
// Post the message
const request = new XMLHttpRequest() ;
request.open("POST", "/upload?o=option") ;
request.send(formData) ;
Performing a Simple Request in Javascript
fetch("/upload?o=option", {method: "POST",body: JSON.stringify({"id": 7,"complete": true}),headers: {"Content-type": "application/json"}});
ESP8266Webserver on
- void on(const Uri &uri, THandlerFunction handler);
- void on(const Uri &uri, HTTPMethod method, THandlerFunction fn);
- void on(const Uri &uri, HTTPMethod method, THandlerFunction fn, THandlerFunction ufn);
void on(const Uri &uri, THandlerFunction handler)
Webserver.on("/get", HTTP_GET, myGetFunction)
WebServer() {on("/handle", HTTP_ANY, WebServer::doHandle) ;}static void doHandle() {Server.doProcess() ;}void doProcess() {switch (method()) {case HTTP_GET:send(200) ;break ;case HTTP_POST:// body of the post is treated specially// note that this is a simple mechanism// and can only handle textString postcontents = arg("plain") ;send(200) ;break ;default:send(500) ;break ;}}
on("/config",HTTP_ANY,[&]() {switch (method()) {case HTTP_GET:serveConfigFile() ;break ;case HTTP_POST:send(400, "text/plain", "Requires multipart/* Content-Type");break ;default:send(405, "text/plain", "Method not supported");break ;}},[&]() {handleConfigUpload() ;});
- Binary uploads are not supported
- The text upload is stored in a string, and the user has no control over memory allocations
Upload Callback Function
upload().filename - name of the file as supplied on the form / in the javascriptupload().name - label of the entry as supplied on the form / in the javascript
upload().type - would have expected this to be the mime type of the object, but it is currently random rubbish (12/08/2023)
Here, the handler needs to close, validate and store the uploaded file.