ESP HTTP SERVER + FILESYSTEM、二 - 0) {
一、html实现变更:
static const char manage_html[] =
"LittleFS Manager"
"
LittleFS File Manager
"
""
"
"
"
";
坑点1:起初ul实现为:
"function ul(){const f=document.getElementById('file').files[0];"
"fetch('/api/upload',{method:'POST',body:new FormData().append('file',f)})"
".then(()=>refresh());}"
这使得ul回调处理错误,找不到字符内容,因此“esp_err_t ret = httpd_req_get_hdr_value_str(req, “Content-Type”, ct, sizeof(ct));”一直判fail。改了多次ul回调后,让AI注意HTML的实现。后续改为:
"function ul(){const f=document.getElementById('file').files[0];"
"fetch('/api/upload',{method:'POST',body:new FormData().append('file',f)})"
".then(()=>refresh());}"
"function ul(){"
"const file = document.getElementById('file').files[0];"
"const fd = new FormData();"
"fd.append('file', file);"
"fetch('/api/upload', {"
" method : 'POST',"
" body : fd"
"})"
".then(resp => resp.text())"
".then(txt => { console.log(txt); refresh(); })"
".catch(err => console.error(err));"
"}"
解决了无法上传问题。 该问题AI的回答是:
问题根源在 HTML 端:
fetch('/api/upload',{method:'POST',body:new FormData().append('file',f)})
这句 并没有设置 Content-Type 头,而浏览器对 显式构造的 FormData 不会自动补 boundary,导致 Edge/Chrome 发出的请求头长这样:
Content-Type: multipart/form-data
缺少 boundary=...,于是 ESP32 端 upload_post_handler 提取 boundary 失败,直接 400。
但是,按照这个说法,实际请求头“Content-Type: multipart/form-data”,不应该导致上述函数判fail。该问题可以深究
upload的实现:
static esp_err_t upload_post_handler(httpd_req_t *req)
{
char buf[UPLOAD_BUF_SIZE];
char boundary[BOUNDARY_MAX] = {0};
char filename[FILENAME_MAX] = {0};
FILE *fp = NULL;
/* 1. 先拿 Content-Type 长度,判空 */
size_t ct_len = httpd_req_get_hdr_value_len(req, "Content-Type");
if (ct_len == 0) {
ESP_LOGW(TAG_UP, "no Content-Type header");
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "need Content-Type");
return ESP_FAIL;
}
/* 2. 再读内容(自动截断到缓冲区大小)*/
char ct[128] = {0};
esp_err_t ret = httpd_req_get_hdr_value_str(req, "Content-Type", ct, sizeof(ct));
if (ret != ESP_OK) {
ESP_LOGW(TAG_UP, "read Content-Type fail %d", ret);
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "read Content-Type fail");
return ESP_FAIL;
}
/* 3. 提取 boundary */
char *bstart = strstr(ct, "boundary=");
if (!bstart) {
ESP_LOGW(TAG_UP, "no boundary");
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "no boundary");
return ESP_FAIL;
}
bstart += 9;
while (*bstart == ' ' || *bstart == '"') bstart++;
char *bend = bstart;
while (*bend && *bend != ';' && *bend != '"' && *bend != '\r' && *bend != '\n') bend++;
int blen = bend - bstart;
if (blen <= 0 || blen >= BOUNDARY_MAX) {
ESP_LOGW(TAG_UP, "bad boundary");
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "bad boundary");
return ESP_FAIL;
}
memcpy(boundary, bstart, blen);
boundary[blen] = '\0';
ESP_LOGI(TAG_UP, "boundary=[%s]", boundary);
/* 4. 拼装尾部 boundary 标志 */
char tail_bnd[80];
snprintf(tail_bnd, sizeof(tail_bnd), "--%s--", boundary);
/* 5. 流式读 body */
bool head_done = false;
int remaining = req->content_len;
while (remaining > 0) {
int recv = httpd_req_recv(req, buf, MIN(remaining, sizeof(buf)));
if (recv <= 0) break;
remaining -= recv;
/* 拼缓存:解决 boundary 跨包 */
int concat_len = g_cache_len + recv;
if (concat_len > CACHE_MAX) concat_len = CACHE_MAX;
memmove(g_cache + g_cache_len, buf, recv);
g_cache_len += recv;
/* 找 filename(仅头段) */
if (!head_done && !filename[0]) {
char *f = memmem(g_cache, g_cache_len, "filename=\"", 10);
if (f) {
f += 10;
char *q = strchr(f, '"');
if (q) {
int len = q - f;
if (len >= FILENAME_MAX) len = FILENAME_MAX - 1; 拼多多帮助力入口
memcpy(filename, f, len);
filename[len] = '\0';
ESP_LOGI(TAG_UP, "upload file name: %s", filename);
}
}
}
/* 找头部结束 \r\n\r\n */
if (!head_done) {
char *hd_end = memmem(g_cache, g_cache_len, "\r\n\r\n", 4);
if (hd_end) {
head_done = true;
char *body_start = hd_end + 4;
int body_now = g_cache_len - (body_start - g_cache);
if (body_now > 0 && filename[0]) {
if (!fp) {
char path[256];
snprintf(path, sizeof(path), "/littlefs/%s", filename);
fp = fopen(path, "wb");
if (!fp) {
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "create failed");
return ESP_FAIL;
}
}
fwrite(body_start, 1, body_now, fp);
}
}
} else {
/* 纯数据段 */
if (filename[0]) {
if (!fp) {
char path[256];
snprintf(path, sizeof(path), "/littlefs/%s", filename);
fp = fopen(path, "wb");
if (!fp) {
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "create failed");
return ESP_FAIL;
}
}
fwrite(g_cache, 1, g_cache_len, fp);
}
}
/* 出现结尾 boundary 就停 */
if (memmem(g_cache, g_cache_len, tail_bnd, strlen(tail_bnd))) {
g_cache_len = 0;
break;
}
/* 保存最后 128 字节,防止分包 */
int keep = (g_cache_len > 128) ? 128 : g_cache_len;
memmove(g_cache, g_cache + g_cache_len - keep, keep);
g_cache_len = keep;
}
if (fp) fclose(fp);
g_cache_len = 0; /* 复位缓存 */
ESP_LOGI(TAG_UP, "upload %s finished", filename[0] ? filename : "");
httpd_resp_sendstr(req, "upload OK");
return ESP_OK;
}
坑点1:
该实现为手搓multipart解析,效果糟糕,起初上传内容总是带有“boundary”头。反复修改实现,越改越糟糕。后面让AI不要再改了,给出新的方式。AI表示认可,“这段逻辑已经连续三次在不同边界条件上翻车,根本原因是 ESP-IDF 的 httpd 解析层不会帮你做 multipart 拆分,而我们用字符串匹配去模拟,边界情况太多(分包、回车位置、空 part、重复 boundary…)——性价比太低。 ”。于是给出了两种方式“别再手搓 multipart 了,换 binary POST,十分钟搞定,零边界问题,零多余内容。 如果仍坚持 multipart,直接移植 mpparser,别再自己拼字符串。”于是我选择了binary POST方式。
static esp_err_t upload_post_handler(httpd_req_t *req)
{
char filename[128] = {0};
/* 从 query 参数拿文件名,无需解析 multipart */
if (httpd_req_get_url_query_str(req, filename, sizeof(filename)) == ESP_OK) {
char *dec = strchr(filename, '=');
if (dec) dec = url_decode(dec + 1);
else dec = "noname.bin";
char path[256];
snprintf(path, sizeof(path), "/littlefs/%s", dec);
FILE *fp = fopen(path, "wb");
if (!fp) {
httpd_resp_send_err(req, HTTPD_500_INTERNAL_SERVER_ERROR, "create failed");
return ESP_FAIL;
}
/* 纯流式拷文件 */
char buf[1024];
int recv;
while ((recv = httpd_req_recv(req, buf, sizeof(buf))) > 0) {
fwrite(buf, 1, recv, fp);
}
fclose(fp);
httpd_resp_sendstr(req, "upload OK");
return ESP_OK;
}
httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, "need fname");
return ESP_FAIL;
}
下载实现:
上传中文文件名后,无法下载和删除。发现是UTF8编码的原因。于是加入了urldecode。 “是的,中文文件名在 URL 里会变成 UTF-8 百分号编码(风景.jpg → %E9%A3%8E%E6%99%AF.jpg), 而 ESP32 端 没做 URL 解码,于是: req->uri = “/api/%E9%A3%8E%E6%99%AF.jpg” 你直接 req->uri + 5 得到的是 百分号编码串, 再 fopen(“/littlefs/%E9%A3%8E%E6%99%AF.jpg”, “rb”) → 文件不存在 → 404。”
最后的下载实现:
/* 返回解码后的字符串(静态缓冲区,线程安全由调用者保证) URL 解码:%E4%BD%A0 → 你*/
static const char *url_decode(const char *src)
{
static char dec[256];
size_t len = strlen(src);
if (len >= sizeof(dec)) len = sizeof(dec) - 1;
size_t di = 0;
for (size_t si = 0; si < len; si++) {
unsigned char c = src[si]; /* 先转无符号 */
if (c == '%' && si + 2 < len) {
unsigned char hi = src[si + 1];
unsigned char lo = src[si + 2];
if (isxdigit(hi) && isxdigit(lo)) {
unsigned char hex = 0;
sscanf((const char[]){ hi, lo, '\0' }, "%2hhx", &hex);
dec[di++] = hex;
si += 2;
continue;
}
}
if (c == '+') {
dec[di++] = ' ';
} else {
dec[di++] = c;
}
}
dec[di] = '\0';
return dec;
}
/* ---------- 2. 文件下载 ---------- */
static esp_err_t api_download_get(httpd_req_t *req)
{
/* 1. 解码 URI 文件名 */
const char *encoded = req->uri + 5; // 去掉 "/api/"
const char *decoded = url_decode(encoded); // 风景.jpg
/* 2. 拼盘内路径 */
char path[256];
snprintf(path, sizeof(path), "/littlefs/%s", decoded);
/* 3. 只许普通文件 */
struct stat st;
if (stat(path, &st) != 0 || !S_ISREG(st.st_mode)) {
httpd_resp_send_404(req);
return ESP_OK;
}
/* 4. 告诉浏览器附件+原名(用编码名,浏览器会自动解) */
httpd_resp_set_hdr(req, "Content-Disposition", "attachment");
httpd_resp_set_type(req, "application/octet-stream");
/* 5. 流式发送 */
FILE *f = fopen(path, "rb");
if (!f) { httpd_resp_send_404(req); return ESP_OK; }
char blk[1024];
size_t n;
while ((n = fread(blk, 1, sizeof(blk), f)) > 0)
httpd_resp_send_chunk(req, blk, n);
httpd_resp_send_chunk(req, NULL, 0); // 结束 chunked
fclose(f);
return ESP_OK;
}
关于此处有个疑问(上传和下载时的utf8编码是否方式不一致),咨询AI得到:
阶段使用的字段编码情况上传FormData 里的 filename=浏览器已按 UTF-8 原样写入,无百分号下载URL 路径 /api/风景.jpg浏览器先做百分号编码 %E9%A3%8E%E6%99%AF.jpg当然了,由于最终采用binary POST方式上传,因此上传回答中仍然要解码文件名。