#include <winsock2.h>
#include <windows.h>
#include <stdio.h>
#include <wininet.h>
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "wininet.lib")
BOOL UseHttpSendReqEx(HINTERNET hConnect, TCHAR *upFile, TCHAR *localFile)
{
INTERNET_BUFFERS BufferIn = {0};
DWORD dwBytesRead;
DWORD dwBytesWritten;
BYTE pBuffer[302480]; // Read from file in 300M chunks,最大支持300M文件
BOOL bRead, bRet;
BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS );
//使用put方式上传文件:
HINTERNET hRequest = HttpOpenRequest(hConnect,
"PUT",
localFile,
NULL,
NULL,
NULL,
INTERNET_FLAG_NO_CACHE_WRITE,
0);
if (!hRequest)
{
printf("Failed to open request handle: %lu\n", GetLastError ());
return FALSE;
}
//打开指定的文件:
HANDLE hFile = CreateFile(upFile, GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
printf("\nFailed to open local file %s.", upFile);
return FALSE;
}
BufferIn.dwBufferTotal = GetFileSize (hFile, NULL);
printf ("File size is %d\n", BufferIn.dwBufferTotal );
if(!HttpSendRequestEx( hRequest, &BufferIn, NULL, HSR_INITIATE, 0))
{
printf( "Error on HttpSendRequestEx %lu\n",GetLastError() );
return FALSE;
}
DWORD sum = 0;
do
{
if (!(bRead = ReadFile (hFile, pBuffer, sizeof(pBuffer),&dwBytesRead, NULL)))
{
printf ("\nReadFile failed on buffer %lu.",GetLastError());
break;
}
if (!(bRet=InternetWriteFile( hRequest, pBuffer, dwBytesRead,&dwBytesWritten)))
{
printf ("\nInternetWriteFile failed %lu", GetLastError());
break;
}
sum += dwBytesWritten;
}
while (dwBytesRead == sizeof(pBuffer)) ;
CloseHandle (hFile);
printf ("Actual written bytes: %d\nupload %s successed!\n", sum,localFile);
//结束一个HTTP请求:
if(!HttpEndRequest(hRequest, NULL, 0, 0))
{
printf( "Error on HttpEndRequest %lu \n", GetLastError());
return FALSE;
}
return TRUE;
}
int main(int argc, char **argv)
{
//put 127.0.0.1 /2.db d:\\1.exe
if(argc!=4)
{
printf("Param num not correct.\n");
return 0;
}
//char *ServerName="127.0.0.1"; //这里填写URL地址
char *ServerName=argv[1];
HINTERNET hSession = InternetOpen("HttpSendRequest",
INTERNET_OPEN_TYPE_PRECONFIG,
NULL,
NULL,
0); //同步方式
if(!hSession)
{
printf("Failed to open InternetOpen\n");
exit(0);
}
//连接到一个http服务:
HINTERNET hConnect = InternetConnect(hSession,
ServerName,
INTERNET_DEFAULT_HTTP_PORT, //连接到80端口
NULL,
NULL,
INTERNET_SERVICE_HTTP, //服务类型HTTP,FTP或Gopher
0,
1);
if(!hConnect)
{
printf("error InternetConnect\n");
return 0;
}
//TCHAR *putfile="d:\\1.exe"; //上传的程序
TCHAR *putfile=argv[3];
TCHAR *putlocalfile=argv[2];
BOOL sigh;
sigh=UseHttpSendReqEx(hConnect,putfile,putlocalfile);
if(!sigh)
{
printf("error UseHttpSendReqEx\n");
return 0;
}
return 0;
}