如何从http请求正文字符串中获取文件名?

时间:2011-08-06 15:14:58

标签: c++ string http find std

所以我尝试这样的代码:

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"我的cede返回Torrent d作为文件名,而它应该返回Torrent downloaded from Demonoid.com.txt。如何修复我的文件上传http请求文件解析器?

1 个答案:

答案 0 :(得分:3)

string::find返回搜索字符串中第一个字符的索引。因此,当您搜索时,它会为您提供ffilename=的索引。

在第

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