#include <Arduino.h>
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <SPIFFS.h>
const char *ssid = "BangBros";
const char *password = "babdigang";
AsyncWebServer server(80);
void setup()
{
Serial.begin(115200);
// Initialize SPIFFS
if (!SPIFFS.begin(true))
{
Serial.println("An error occurred while mounting SPIFFS");
return;
}
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
Serial.print("HTTP server started at http://");
Serial.println(WiFi.localIP());
// Serve the HTML file as the default route
server.on("/", HTTP_GET, [](AsyncWebServerRequest *request)
{
File file = SPIFFS.open("/file_upload.html", "r");
if (!file) {
request->send(404, "text/plain", "File Not Found");
Serial.println("file_upload.html file not found");
} else {
request->send(SPIFFS, "/file_upload.html", "text/html");
Serial.println("Serving file_upload.html");
} });
// Route to handle file upload
server.on("/upload", HTTP_POST, [](AsyncWebServerRequest *request){
AsyncWebServerResponse *response;
// Check if the request has a file attached
if (request->hasParam("update", true))
{
AsyncWebParameter *p = request->getParam("update", true);
String filename = p->value();
filename = "/" + filename;
// Open the file for writing
File file = SPIFFS.open(filename, "w");
if (!file)
{
Serial.println("Failed to open file for writing");
response = request->beginResponse(500, "text/plain", "Error opening file.");
}
else
{
// Write the file content
String fileData = p->value();
file.print(fileData);
file.close();
Serial.println("File written");
response = request->beginResponse(200, "text/plain", "File Upload Success");
}
}
else
{
response = request->beginResponse(400, "text/plain", "No file data received.");
}
response->addHeader("Connection", "close");
request->send(response);
}
// Start server
server.begin();
}
void loop()
{
// Your code here
}