简体   繁体   English

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

[英]How to get filename from http request body string?

So I try such code: 所以我尝试这样的代码:

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();

But it outputs in for example: 但是它输出例如:

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

This means that from filename="Torrent downloaded from Demonoid.com.txt" my cede returnes Torrent d as a file name while it should return Torrent downloaded from Demonoid.com.txt . 这意味着从filename="Torrent downloaded from Demonoid.com.txt"我的filename="Torrent downloaded from Demonoid.com.txt"返回Torrent d作为文件名,而它应该返回Torrent downloaded from Demonoid.com.txt How to fix my file upload http request filename parser? 如何修复我的文件上传http请求文件名解析器?

string::find returns the index of the first character in the search string . string::find返回搜索字符串中第一个字符的索引。 So it's giving you the index of the f in filename= when you search for that. 因此,当您搜索filename=时,它将为filename=中的f提供索引。

In the line 在行中

size_t  end_of_file_name = request->body.find("\"",found_file + 1);

You'll have to change that to 您必须将其更改为

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 "

Then change 然后改变

std::string filename(request->body, found_file+10, end_of_file_name - found_file);

To

std::string filename(request->body, found_file + 10, end_of_file_name - (found_file + 10));

You might want to add another variable to quit having to add 10 all the time as well. 您可能想要添加另一个变量以退出,而必须一直添加10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM