stu*_*ent 2 c++ upload http file wininet
我想将"C:\ test.txt"上传到网络服务器,当我运行程序时,文件没有上传,我没有收到任何错误.
和webserver上的php代码可以在这里找到:" http://student114.110mb.com/upload.txt "或" http://student114.110mb.com/upload.php "
请在我做错的地方帮助我
#include <windows.h>
#include <wininet.h>
#include <tchar.h>
#include <iostream>
#pragma comment(lib,"wininet.lib")
using namespace std;
int main()
{
static TCHAR frmdata[] = "-----------------------------7d82751e2bc0858\nContent-Disposition: form-data; name=\"uploadedfile\"; filename=\"C:\test.txt\"\nContent-Type: text/plain\n\nfile contents here\n-----------------------------7d82751e2bc0858--";
static TCHAR hdrs[] = "Content-Type: multipart/form-data; boundary=---------------------------7d82751e2bc0858";
HINTERNET hSession = InternetOpen("MyAgent",INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if(hSession==NULL)
{
cout<<"Error: InternetOpen";
}
HINTERNET hConnect = InternetConnect(hSession, _T("localhost"),INTERNET_DEFAULT_HTTP_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 1);
if(hConnect==NULL)
{
cout<<"Error: InternetConnect";
}
HINTERNET hRequest = HttpOpenRequest(hConnect, (const char*)"POST",_T("upload.php"), NULL, NULL, (const char**)"*/*\0", 0, 1);
if(hRequest==NULL)
{
cout<<"Error: HttpOpenRequest";
}
BOOL sent= HttpSendRequest(hRequest, hdrs, strlen(hdrs), frmdata, strlen(frmdata));
if(!sent)
{
cout<<"Error: HttpSendRequest";
}
//close any valid internet-handles
InternetCloseHandle(hSession);
InternetCloseHandle(hConnect);
InternetCloseHandle(hRequest);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我能够使你的代码工作.
首先,您提供的链接上的代码和您发布的代码不一样:
InternetConnect(hSession, _T("localhost"), ...
InternetConnect(hSession, _T("http://student114.110mb.com"), ...
Run Code Online (Sandbox Code Playgroud)
你必须在这里传递一个主机名或IP地址,所以"localhost"是好的,但" http://student114.110mb.com "不是.如果您传递URL,您将收到12005错误代码[ 请参阅msdn上的WinINet错误代码].
另一个问题是frmdata字符串.您应该在C:\ test.txt中加倍反斜杠,否则您将在字符串中得到制表符\ t.分隔符之前和之后的\n也应该由\ r \n替换,因为RFC 1521和大多数其他Internet协议使用CRLF作为行分隔符.
这是我用过的字符串.
static TCHAR frmdata[] = "-----------------------------7d82751e2bc0858\r\nContent-Disposition: form-data; name=\"uploadedfile\"; filename=\"C:\\test.txt\"\r\nContent-Type: text/plain\r\n\r\nfile contents here\r\n-----------------------------7d82751e2bc0858--\r\n";
Run Code Online (Sandbox Code Playgroud)
最后PHP代码不起作用,因为你使用$ _FILES ["file"]你应该使用$ _FILES ["uploadedfile"]."uploadedfile"通常对应于HTML中<input type ="file">标记的名称,但在您的情况下,它在frmdata []字符串的name =参数中指定.
这是我用来测试它的PHP代码
move_uploaded_file($_FILES["uploadedfile"]["tmp_name"], "/files/my_file");
Run Code Online (Sandbox Code Playgroud)
当您处理这样复杂的客户端/服务器交互时,它有助于分别测试每个部分.你可以举个例子.
写一个简单的HTML上传表单来测试你的php脚本
让您的程序将其请求发送到netcat并检查输出