Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/*********
Rui Santos
Complete project details at https://randomnerdtutorials.com
*********/
// Import required libraries
#include "WiFi.h"
#include "ESPAsyncWebServer.h"
#include "SPIFFS.h"
// Replace with your network credentials
const char* ssid = "REPLACE_WITH_YOUR_SSID";
const char* password = "REPLACE_WITH_YOUR_PASSWORD";
AsyncWebServer server(80);
const char index_html_1[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h2>Main web-page</h2>
<p>
<a href="/show"><button>Show</button></a>
</p>
</html>)rawliteral";
const char index_html_2[] PROGMEM = R"rawliteral(
<!DOCTYPE HTML><html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h2>File content</h2>
<p id="file-content"></p>
</body>
<script>
window.addEventListener('load', getFile);
function getFile(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
document.getElementById("file-content").innerHTML=this.responseText;
}
};
xhr.open("GET", "/get-file", true);
xhr.send();
}
</script>
</html>)rawliteral";
// Initialize SPIFFS
void initSPIFFS() {
if (!SPIFFS.begin()) {
Serial.println("An error has occurred while mounting SPIFFS");
}
Serial.println("SPIFFS mounted successfully");
}
void setup(){
// Serial port for debugging purposes
Serial.begin(115200);
initSPIFFS();
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi..");
}
// Print ESP32 Local IP Address
Serial.println(WiFi.localIP());
// Route for root / web page
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html_1);
});
server.on("/show", HTTP_GET, [](AsyncWebServerRequest *request){
request->send_P(200, "text/html", index_html_2);
});
server.on("/get-file", HTTP_GET, [](AsyncWebServerRequest *request){
request->send(SPIFFS, "/data.txt", "text/txt");
});
// Start server
server.begin();
}
void loop(){
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment