2011-08-06 159 views
0

因此,我想這樣的代碼:如何從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請求文件名解析器?

回答

3

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