Untitled

 avatar
unknown
c_cpp
20 days ago
2.9 kB
5
Indexable
#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <SPIFFS.h>
const char* ssid = "";
const char* password = "";


AsyncWebServer server(80);
const char* BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

std::vector<uint8_t> base64Decode(const String &input) {
    if (input.length() == 0) return {}; 
    int len = input.length();
    int padding = 0;
    if (len > 1 && input[len - 1] == '=') padding++;
    if (len > 2 && input[len - 2] == '=') padding++;

    std::vector<uint8_t> output;
    output.reserve((len * 3) / 4 - padding);

    uint32_t buffer = 0;
    int bitsCollected = 0;

    for (char c : input) {
        if (c == '=') break;
        const char* pos = strchr(BASE64_CHARS, c);
        if (!pos) continue;

        buffer = (buffer << 6) | (pos - BASE64_CHARS);
        bitsCollected += 6;

        if (bitsCollected >= 8) {
            bitsCollected -= 8;
            output.push_back((buffer >> bitsCollected) & 0xFF);
        }
    }
    return output;
}

void handleImageUpload(void *parameter) {
    AsyncWebServerRequest *request = (AsyncWebServerRequest *)parameter;
    if (request->hasParam("image", true)) {
        String imageData = request->getParam("image", true)->value();
        imageData.replace("data:image/jpeg;base64,", "");

        std::vector<uint8_t> decodedData = base64Decode(imageData);
        if (decodedData.empty()) {
            request->send(400, "text/plain", "Błąd dekodowania zdjęcia!");
            vTaskDelete(NULL);
            return;
        }

        File file = SPIFFS.open("/przetworzone_zdjecie.jpg", FILE_WRITE);
        if (!file) {
            request->send(500, "text/plain", "Błąd otwarcia pliku!");
            vTaskDelete(NULL);
            return;
        }

        file.write(decodedData.data(), decodedData.size());
        file.close();

        request->send(200, "text/plain", "Zdjęcie zostało zapisane!");
    } else {
        request->send(400, "text/plain", "Brak danych zdjęcia!");
    }
    vTaskDelete(NULL);
}

void setup() {
    Serial.begin(115200);
    
    if (!SPIFFS.begin(true)) {
        Serial.println("Błąd inicjalizacji SPIFFS!");
        return;
    }

    WiFi.begin(ssid, password);
    Serial.print("Łączenie z Wi-Fi...");
    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.print(".");
    }
    Serial.println("\nPołączono z Wi-Fi!");
    Serial.println("Adres IP: " + WiFi.localIP().toString());

    server.serveStatic("/", SPIFFS, "/").setDefaultFile("index.html");
    server.on("/upload", HTTP_POST, [](AsyncWebServerRequest *request) {
        xTaskCreatePinnedToCore(handleImageUpload, "HandleImageUpload", 8192, request, 1, NULL, 1);
    });

    server.begin();
}


void loop() {
    delay(10);
}
Editor is loading...
Leave a Comment