简体   繁体   中英

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 . How to fix my file upload http request filename parser?

string::find returns the index of the first character in the search string . So it's giving you the index of the f in filename= when you search for that.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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