如何从http请求体字符串获取文件名

How to get filename from http request body string?

本文关键字:字符串 获取 文件名 请求 http      更新时间:2023-10-16

所以我尝试这样的代码:

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请求文件名解析器?

string::find返回搜索字符串中第一个字符的索引。所以当你搜索filename=的时候它会给你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