Arduino IDE中定义文件名变量并插入HTTP请求头上传至Flask应用
Arduino动态生成Content-Disposition请求头问题
在Arduino IDE中,需将文件名定义为变量并插入HTTP请求头,实现向Flask应用上传文件。硬编码文件名的代码可正常运行:
if (https.begin(*client, "https://hanspeter//")) { https.addHeader("Content-Type", "image/jpeg"); https.addHeader("Content-Disposition", "inline; filename=\"1\""); }
但尝试多种变量定义方式均报错,以下是错误方案及对应报错信息:
错误方案1
const char *thisisaname = "1"; https.addHeader("Content-Disposition", "inline; filename="thisisaname);
错误信息:
无法找到字符串字面量运算符operator""thisisaname,参数类型为const char [18]、unsigned int
错误方案2
const char *thisisaname = "1"; https.addHeader("Content-Disposition", "inline; filename=\"" + thisisaname + "\"");
错误信息:
二元运算符+的操作数类型无效,分别为const char [19]和const char*
错误方案3
const char *thisisaname = "\"1\""; https.addHeader("Content-Disposition", "inline; filename="thisisaname);
错误信息:
二元运算符+的操作数类型无效,分别为const char [19]和const char*
正确解决方法
Arduino的C++环境中无法直接拼接C风格字符串(const char*),可通过以下方式实现动态生成请求头:
方法1:使用String类拼接
const char *thisisaname = "1"; String dispositionHeader = "inline; filename=\"" + String(thisisaname) + "\""; https.addHeader("Content-Disposition", dispositionHeader.c_str());
方法2:直接用String变量存储文件名
String filename = "1"; String dispositionHeader = "inline; filename=\"" + filename + "\""; https.addHeader("Content-Disposition", dispositionHeader.c_str());
方法3:用snprintf格式化C风格字符串(节省内存)
const char *thisisaname = "1"; char headerBuffer[64]; // 定义足够容纳完整头内容的缓冲区 snprintf(headerBuffer, sizeof(headerBuffer), "inline; filename=\"%s\"", thisisaname); https.addHeader("Content-Disposition", headerBuffer);
内容的提问来源于stack exchange,提问作者Natrium2
相关产品推荐
相关产品推荐

