form-data not working in C++ in request when body has text fields
way4sahil opened this issue · comments
if (request.has_param("featureID") && request.has_param("data") && request.has_param("timestamp"))
{
}
request.params is not able to recognize the data coming as form data
Has someone faces this?
Hope the following info helps.
https://github.com/yhirose/cpp-httplib?tab=readme-ov-file#post-with-multipart-form-data
Hi @yhirose
it is able to read the files coming as formdata, but not the text fields, and it is reading those text fields as file only, even though it is not a file.
curl --location '' --form 'id=value' --form 'priority=1' --form 'timestamp=123456' --form 'connectionType=wifi' --form 'file=@'
It is able to read the file but not the other params like id ,priority etc.
svr.Post("/testserver", [](const httplib::Request& req, httplib::Response& res) {
// Handle text fields
std::cout << "Text fields received:" << std::endl;
for (const auto& item : req.params) {
std::cout << item.first << " = " << item.second << std::endl;
}
// Handle file uploads
std::cout << "Files received:" << std::endl;
for (const auto& file : req.files) {
std::cout << "Uploaded file key: " << file.first << "; Filename: " << file.second.filename << std::endl;
// Optionally save the file
// file.second.save_to("/path/to/save/" + file.second.filename); // Uncomment if needed
}
// Set a response
res.set_content("Form data processed", "text/plain");
});
Output :
Text fields received:
Files received:
Uploaded file key: connectionType; Filename:
Uploaded file key: data; Filename:
Uploaded file key: featureID; Filename:
Uploaded file key: priority; Filename:
Uploaded file key: timestamp; Filename:
curl --location '' --form 'featureID=<>' --form 'priority=1' --form 'timestamp=123456' --form 'connectionType=wifi' --form 'file='
It is taking all textfields as file, it is a bug
Anyway the workaround is :
std::cout << "Files received:" << std::endl;
for (const auto& file : req.files) {
std::cout << "Uploaded file key: " << file.first << "; Filename: " << file.second.content << std::endl;
// Optionally save the file
// file.second.save_to("/path/to/save/" + file.second.filename); // Uncomment if needed
}
Just read it as a file and the content is the text value.
Please take this up if required @yhirose Thanks,