不,您不需要以 HEX 格式发送文件数据。您需要按原样发送文件的原始原始二进制数据。std::string
假设文件的大小很小,您可以将其按原样填充。
\r\n
顺便说一句,您的请求格式不正确 - 您的Connection
标题太多了。额外的\r\n
属于最后一个标题之后。并且不要使用Content-Length
带有multipart
内容类型的标头,因为它们会自行终止 - 特别是因为您无论如何都指定了错误的值。如果要指定 a Content-Length
,则必须先计算完整 MIME 数据的长度,然后再创建继续它的标头。
试试这个:
std::ifstream File("filename", std::ios::in | std::ios::binary | std:::ios::ate);
if (file)
{
std::ifstream::pos_type FileSize = File.tellp();
File.seekg(0);
std::string StrData;
if (FileSize > 0)
{
StrData.resize(FileSize);
File.read(&StrData[0], FileSize);
}
File.close();
std::string query =
"POST /test/upload.php HTTP/1.1\r\n"
"Host: site.net\r\n"
"User-Agent: User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36\r\n"
"Connection: Keep-alive\r\n"
"Content-Type: multipart/form-data; boundary=----WebKitFormBoundarym9PgiUg6fjxm2Hpr\r\n"
"\r\n"
"------WebKitFormBoundarym9PgiUg6fjxm2Hpr\r\n"
"Content-Disposition: form-data; name=\"tmp\"; filename=\"photo.jpg\"\r\n"
"Content-Type: image/jpeg\r\n"
"\r\n"
+StrData+
"\r\n"
"------WebKitFormBoundarym9PgiUg6fjxm2Hpr--\r\n";
// send query ...
}
话虽如此,最好不要尝试将整个 HTTP 请求填充到单个std::string
. 首先发送初始请求标头,然后发送原始文件数据,最后发送终止边界。例如:
std::fstream File("filename", std::ios::in | std::ios::binary);
if (file)
{
char chunk[1024];
std::streamsize chunksize;
std::string str =
"POST /test/upload.php HTTP/1.1\r\n"
"Host: site.net\r\n"
"User-Agent: User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.116 Safari/537.36\r\n"
"Connection: Keep-alive\r\n"
"Content-Type: multipart/form-data; boundary=----WebKitFormBoundarym9PgiUg6fjxm2Hpr\r\n"
"\r\n"
"------WebKitFormBoundarym9PgiUg6fjxm2Hpr\r\n"
"Content-Disposition: form-data; name=\"tmp\"; filename=\"photo.jpg\"\r\n"
"Content-Type: image/jpeg\r\n"
"\r\n";
// send str ...
do
{
chunksize = File.readsome(chunk, sizeof(chunk));
if (chunksize < 1)
break;
// send chunk up to chunksize bytes ...
}
while (true);
File.close();
str =
"\r\n"
"------WebKitFormBoundarym9PgiUg6fjxm2Hpr--\r\n";
// send str ...