Como deletar um arquivo do LittleFS do ESP32 via HTTP REST API

Este post mostra como implementar um endpoint DELETE num ESP32 (esp_http_server do ESP-IDF) que remove um arquivo do LittleFS, e como chamá-lo com curl.

O endpoint

example.txt
DELETE /api/files/delete?path=<relative/path>

O handler sanitiza o path (rejeita .., remove barras iniciais), recusa deletar arquivos de sistema protegidos e retorna 404 se o arquivo não existe.

Handler de firmware (ESP-IDF)

HTTPHandlersFiles.cpp
esp_err_t handleDeleteFile(httpd_req_t *req) {
    // Expect DELETE /api/files/delete?path=<relative/path>
    QueryURLParser parser(req);
    if (!parser.HasParameter("path")) {
        httpd_resp_set_status(req, "400 Bad Request");
        httpd_resp_sendstr(req, "{\"error\": \"Missing path parameter\"}");
        return ESP_OK;
    }

    std::string rel = parser.GetParameter("path");
    if (!sanitize_path(rel, rel) || rel.empty()) {
        httpd_resp_set_status(req, "400 Bad Request");
        httpd_resp_sendstr(req, "{\"error\": \"Invalid path\"}");
        return ESP_OK;
    }

    // Protect internal files from external deletion
    if (rel == "nodes.json") {
        httpd_resp_set_status(req, "403 Forbidden");
        httpd_resp_sendstr(req, "{\"error\": \"forbidden\"}");
        return ESP_OK;
    }

    std::string fullpath = std::string(LittleFSManager::mountPoint()) + "/" + rel;
    if (unlink(fullpath.c_str()) != 0) {
        httpd_resp_set_status(req, "404 Not Found");
        httpd_resp_sendstr(req, "{\"error\": \"File not found or deletion failed\"}");
        return ESP_OK;
    }

    set_content_type_with_charset(req, "application/json");
    httpd_resp_sendstr(req, "{\"status\":\"deleted\"}");
    return ESP_OK;
}

Registre-o no servidor HTTP:

HTTPServerWrapper.cpp
static const httpd_uri_t deleteFileHandler = {
    .uri       = "/api/files/delete",
    .method    = HTTP_DELETE,
    .handler   = handleDeleteFile,
    .user_ctx  = NULL
};
httpd_register_uri_handler(server, &deleteFileHandler);

Deletar um arquivo com curl

delete.sh
curl -X DELETE "http://10.56.11.162/api/files/delete?path=lfs_test.txt"

Resposta de sucesso:

response.json
{"status":"deleted","path":"lfs_test.txt"}

Se o arquivo não existe:

error.txt
HTTP/1.1 404 Not Found
{"error": "File not found or deletion failed"}

Notas

  • Sempre sanitize ?path= antes de passá-lo a unlink() — veja a implementação de sanitize_path em Como enviar um arquivo para o LittleFS do ESP32 via HTTP REST API.
  • Mantenha uma denylist explícita para arquivos que o próprio firmware gerencia (ex. um registro nodes.json), senão clientes remotos podem brickar o estado do dispositivo.

Posts relacionados


Check out similar posts by category: ESP32 C/C++