如何从http请求正文字符串获取文件名?
问题描述:
因此,我想这样的代码:如何从http请求正文字符串获取文件名?
std::ofstream myfile;
myfile.open ("example.txt", std::ios_base::app);
myfile << "Request body: " << request->body << std::endl << "Request size: " << request->body.length() << std::endl;
size_t found_file = request->body.find("filename=");
if (found_file != std::string::npos)
{
size_t end_of_file_name = request->body.find("\"",found_file + 1);
if (end_of_file_name != std::string::npos)
{
std::string filename(request->body, found_file+10, end_of_file_name - found_file);
myfile << "Filename == " << filename << std::endl;
}
}
myfile.close();
但例如在输出:
Request body: ------WebKitFormBoundary0tbfYpUAzAlgztXL
Content-Disposition: form-data; name="datafile"; filename="Torrent downloaded from Demonoid.com.txt"
Content-Type: text/plain
Torrent downloaded from http://www.Demonoid.com
------WebKitFormBoundary0tbfYpUAzAlgztXL--
Request size: 265
Filename == Torrent d
这意味着,从filename="Torrent downloaded from Demonoid.com.txt"
我半寸returnes Torrent d
作为文件名,而它应该返回Torrent downloaded from Demonoid.com.txt
。如何解决我的文件上传http请求文件名解析器?
答
string::find
返回搜索字符串中第一个字符的索引。因此,当您搜索该文件时,它会在中为您提供f
的索引。
在行
size_t end_of_file_name = request->body.find("\"",found_file + 1);
你必须要改变,要
size_t end_of_file_name = request->body.find("\"", found_file + 9 + 1); // 9 because that's the length of "filename=" and 1 to start at the character after the "
然后改变
std::string filename(request->body, found_file+10, end_of_file_name - found_file);
要
std::string filename(request->body, found_file + 10, end_of_file_name - (found_file + 10));
您可能想要添加另一个变量以退出,并且必须始终添加10
。