本文展示如何在 ESP32(ESP-IDF esp_http_server)上实现一个 PUT 端点:把请求 body 写进 LittleFS 文件,以及如何用 curl 上传文件。
端点
example.txt
PUT /api/files/put?path=<relative/path>请求 body 是原始文件内容。handler 净化路径(拒绝 ..、剥掉前导斜杠和查询串)、按需创建父目录,并以 1 KiB 块流式写入 flash。
固件 handler(ESP-IDF)
HTTPHandlersFiles.cpp
esp_err_t handlePutFile(httpd_req_t *req) {
// Expect PUT /api/files/put?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;
}
std::string fullpath = std::string(LittleFSManager::mountPoint()) + "/" + rel;
ensure_parent_dirs(fullpath);
FILE* f = fopen(fullpath.c_str(), "wb");
if (!f) {
httpd_resp_set_status(req, "500 Internal Server Error");
httpd_resp_sendstr(req, "{\"error\": \"Failed to open file for writing\"}");
return ESP_OK;
}
const int len = req->content_len;
int received = 0;
char buffer[1024];
while (received < len) {
int to_read = std::min((int)sizeof(buffer), len - received);
int ret = httpd_req_recv(req, buffer, to_read);
if (ret <= 0) {
fclose(f);
httpd_resp_set_status(req, "500 Internal Server Error");
httpd_resp_sendstr(req, "{\"error\": \"Failed to read request body\"}");
return ESP_OK;
}
fwrite(buffer, 1, ret, f);
received += ret;
}
fclose(f);
set_content_type_with_charset(req, "application/json");
httpd_resp_sendstr(req, "{\"status\":\"success\"}");
return ESP_OK;
}注册到 HTTP 服务器:
HTTPServerWrapper.cpp
static const httpd_uri_t putFileHandler = {
.uri = "/api/files/put",
.method = HTTP_PUT,
.handler = handlePutFile,
.user_ctx = NULL
};
httpd_register_uri_handler(server, &putFileHandler);用 curl 上传文件
upload.sh
curl -X PUT --data-binary @index.html \
"http://10.56.11.162/api/files/put?path=index.html"响应:
response.json
{"status":"success","path":"index.html"}重要: 发定长 body。如果你的 HTTP 客户端用 Transfer-Encoding: chunked(如 Python requests 配生成器 body),esp_http_server 可能以 400 Bad Request 拒绝,因为 req->content_len 依赖正确的 Content-Length 头。curl --data-binary @file 会正确发送 Content-Length。
重要:净化路径
绝不要把 ?path= 直接拼到文件系统路径上——否则 path=../../etc/passwd 式遍历能逃出 LittleFS 挂载点。一个最小净化器:
HTTPHandlersFiles.cpp
bool sanitize_path(const std::string &in, std::string &out) {
std::string dec = url_decode(in);
// strip query string and fragment
size_t qpos = dec.find('?');
if (qpos != std::string::npos) dec = dec.substr(0, qpos);
size_t hpos = dec.find('#');
if (hpos != std::string::npos) dec = dec.substr(0, hpos);
// strip leading slashes -> always relative to mount point
size_t start = 0;
while (start < dec.size() && dec[start] == '/') start++;
out = dec.substr(start);
if (out.find("..") != std::string::npos) return false;
return true;
}验证上传
上传后用 CRC32 端点验证完整性——见如何用 CRC32 端点验证 ESP32 LittleFS 的 HTTP 文件上传。
相关文章
如果这篇文章对您有帮助,请考虑请我喝杯咖啡或通过 PayPal 捐款,以支持 TechOverflow 上新文章的研究与发布