如何通过spffi将数据从html检索到esp32



通过spiffs,我能够托管一个web服务器,在该服务器中我创建了一个简单的表单,请求用户输入。我面临着一个问题,我尝试了很多解决方案,看到了很多文章,但他们在草图中使用了html。因此,基本上,我需要从用户在html表单上输入的任何数据中获取数据,并且应该将其禁用到串行监视器。我使用的是Arduino IDE。这是我的密码。

#include "WiFi.h"
#include "SPIFFS.h"
#include "ESPAsyncWebServer.h"

const char* ssid = "ramesh";
const char* password =  "rameshlike";

AsyncWebServer server(80);

void setup(){
Serial.begin(115200);

if(!SPIFFS.begin()){
Serial.println("An Error has occurred while mounting SPIFFS");
return;
}

WiFi.begin(ssid, password);

while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}

Serial.println(WiFi.localIP());

server.on("/html", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(SPIFFS, "/test_file.html", "text/html");
});

server.begin();
}

void loop(){}

这是我的html代码

<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<script>
function message_popup() {
alert("Saved value to ESP SPIFFS");
setTimeout(function(){ document.location.reload(false); }, 500);   
}
</script>
</head>
<body>


<form action="/get" target="hidden-form">
Enter string  <input type="text" name="input_string">
<input type="submit" value="Submit" onclick="message_popup()">
</form><br>
<form action="/get" target="hidden-form">
Enter Integer  <input type="number " name="input_int">
<input type="submit" value="Submit" onclick="message_popup()">
</form><br>
<form action="/get" target="hidden-form">
Enter Floating value <input type="number " name="input_float">
<input type="submit" value="Submit" onclick="message_popup()">
</form>
<iframe style="display:none" name="hidden-form"></iframe>

</body>

</html>

html文件正在web服务器上完美加载。但我找不到资源来获取数据并将其打印在串行监视器上。

简单HTML表单:

<form action="POST" target="/someURL">
<input type="text" placeholder="someText" name="someText">
<button type="submit">Submit Form</button>
</form>

简单端点:

// add a handler to an endpoint URL
// in here the second param must match with the form action
server.on("/someURL", HTTP_POST, [](AsyncWebServerRequest *request){
// get the param count.
int params = request->params();
// loop over the params.
for(int i=0;i<params;i++){
// get a reference to the param object at index.
AsyncWebParameter* p = request->getParam(i);
// print param values.
Serial.printf(
"name: %snvalue:%sn",
p->name().c_str(),p->value().c_str()
);
}
// always respond to the client with something!
request->send(200,"text/plain","Got it!");
});

注意,在您的表单中,您必须指定操作,GET、POST、PUT或其他什么,以及目标url,在本例中为"/someURL";在该表单中,每个输入都应该有一个name属性,submit按钮必须有一个submit类型。

哦,还有一件事,用LittleFs代替SPIFFS。它的工作原理与SPIFFS完全相同,但速度更快、可靠性更高。此外,SPIFFS也被弃用,LittleFs也被内置。

在这里,您可以学习EspAsyncWebserver提供的一切:https://github.com/me-no-dev/ESPAsyncWebServer#body-数据处理

此代码未经测试,只是向您展示一些想法的示例

最新更新