如何 ESP8266/ESP32 上的 SPIFFS 文件中的 "find and replace" 字符串?
How to "find and replace" strings in a file from SPIFFS on ESP8266/ESP32?
我是 运行 ESP-32 上的一个小型网络服务器,闪存上的 HTML 文件通过 SPIFFS 访问它。我有一些状态字段,我想将其动态插入到静态 HTML 文件中。因此,我定义了一些自定义占位符,如 {data_recv}
和 {data_sent}
,它们应该由代码中的字段值替换,然后由 Web 服务器提供给客户端浏览器。
当客户端浏览器请求 HTML 页面之一时,我将使用 SPIFFS 读取它们,例如:
if(SPIFFS.exists(path)) { // if the file exists
File file = SPIFFS.open(path, "r"); // open it
// TODO: replace placeholders {data_recv} and {data_sent} with field values ...
size_t sent = server.streamFile(file, contentType); // and send it to the client
file.close(); // then close the file again
return true;
}
关于如何为 File
类型实现 "find-and-replace" 函数的一些想法?
具有以下函数签名的东西:
bool findAndReplace(File file, String searchStr, String replaceStr) {
// implementation ...
}
我的建议是不要重写文件,而是在回答请求时替换值。
您可以使用缓冲区来使用 fread(buffer, 1, len, file)
逐块读取文件,而不是使用 server.streamFile(file, contentType)
,替换缓冲区中的模式(棘手的部分是您必须跟踪缓冲区末尾的部分匹配)并将缓冲区发送给客户端。
- 正如@dandavid 在评论中所说,您不需要分析
bootstrap.css
或其他静态文件。
- 您可以使用静态 HTML 并使用 JavaScript 更新占位符:执行
XMLHttpRequest
查询。所以你只需要实现一个路径 returns a JSON 每个占位符的值。
我是 运行 ESP-32 上的一个小型网络服务器,闪存上的 HTML 文件通过 SPIFFS 访问它。我有一些状态字段,我想将其动态插入到静态 HTML 文件中。因此,我定义了一些自定义占位符,如 {data_recv}
和 {data_sent}
,它们应该由代码中的字段值替换,然后由 Web 服务器提供给客户端浏览器。
当客户端浏览器请求 HTML 页面之一时,我将使用 SPIFFS 读取它们,例如:
if(SPIFFS.exists(path)) { // if the file exists
File file = SPIFFS.open(path, "r"); // open it
// TODO: replace placeholders {data_recv} and {data_sent} with field values ...
size_t sent = server.streamFile(file, contentType); // and send it to the client
file.close(); // then close the file again
return true;
}
关于如何为 File
类型实现 "find-and-replace" 函数的一些想法?
具有以下函数签名的东西:
bool findAndReplace(File file, String searchStr, String replaceStr) {
// implementation ...
}
我的建议是不要重写文件,而是在回答请求时替换值。
您可以使用缓冲区来使用 fread(buffer, 1, len, file)
逐块读取文件,而不是使用 server.streamFile(file, contentType)
,替换缓冲区中的模式(棘手的部分是您必须跟踪缓冲区末尾的部分匹配)并将缓冲区发送给客户端。
- 正如@dandavid 在评论中所说,您不需要分析
bootstrap.css
或其他静态文件。 - 您可以使用静态 HTML 并使用 JavaScript 更新占位符:执行
XMLHttpRequest
查询。所以你只需要实现一个路径 returns a JSON 每个占位符的值。