18,356
社区成员
发帖
与我相关
我的任务
分享
#include "StdAfx.h"
#include ".\uploadfile.h"
UpLoadFile::UpLoadFile(void)
{
}
UpLoadFile::~UpLoadFile(void)
{
}
BOOL UpLoadFile::UseHttpSendReqEx(CHttpFile* httpFile, DWORD dwPostSize,CString strLocalFile)
{
try
{
DWORD dwRead,dwRet;
BYTE* buffer;
TRACE("Local file:%s\n",strLocalFile);
FILE* fLocal;
if((fLocal=fopen(strLocalFile,"rb"))==NULL)
{
TRACE("Can't open the file:%s,maybe it doesn't exist!\n",strLocalFile);
return false;
}
fseek(fLocal,0L,SEEK_END);
dwRead=ftell(fLocal);
rewind(fLocal);
buffer=(BYTE *)malloc(dwRead);
if(!buffer){
TRACE("not enough memory!\n");
return false;
}
TRACE("length of file:%d\n",dwRead);
dwRead=fread(buffer,1,dwRead,fLocal);
dwPostSize=dwRead;
INTERNET_BUFFERS BufferIn;
DWORD dwBytesWritten;
BOOL bRet;
BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS ); // Must be set or error will occur
BufferIn.Next = NULL;
BufferIn.lpcszHeader = NULL;
BufferIn.dwHeadersLength = 0;
BufferIn.dwHeadersTotal = 0;
BufferIn.lpvBuffer = NULL;
BufferIn.dwBufferLength = 0;
BufferIn.dwBufferTotal = dwPostSize; // This is the only member used other than dwStructSize
BufferIn.dwOffsetLow = 0;
BufferIn.dwOffsetHigh = 0;
httpFile->SendRequestEx(&BufferIn,NULL,HSR_INITIATE,0);
//httpFile->SendRequestEx(dwPostSize);
httpFile->Write( buffer, dwPostSize);
if(!httpFile->EndRequest(0,0,0))
{
TRACE( "Error on HttpEndRequest %lu \n", GetLastError());
return FALSE;
}
fclose(fLocal);
free(buffer);
return TRUE;
}
catch (CInternetException* pEx)
{
//catch errors from WinInet
}
return FALSE;
}
BOOL UpLoadFile::Upload(CString strLocalFile,CString strServerIP,CString strServerPort,CString strRemoteFile)
{
try
{
DWORD dwPostSize=0;
INTERNET_PORT intServerPort=atoi(strServerPort);
CInternetSession internetSession("my session");
CHttpConnection* httpConnection = internetSession.GetHttpConnection(strServerIP,intServerPort);
if(httpConnection == NULL)
{
TRACE( "Failed to connect\n" );
return FALSE;
}
CHttpFile* httpFile = httpConnection->OpenRequest(CHttpConnection::HTTP_VERB_PUT,strRemoteFile,NULL,0,NULL,NULL,INTERNET_FLAG_DONT_CACHE);
//CHttpFile* httpFile = httpConnection->OpenRequest(CHttpConnection::HTTP_VERB_PUT,strRemoteFile);
if(httpFile == NULL)
{
TRACE( "Failed to open request handle\n" );
return FALSE;
}
if(UseHttpSendReqEx(httpFile, dwPostSize,strLocalFile))
{
TRACE( "\nSend Finished.\n" );
httpFile->Close();
httpConnection->Close();
internetSession.Close();
return TRUE;
}
httpFile->Close();
httpConnection->Close();
internetSession.Close();
}
catch (CInternetException* pEx)
{
//catch errors from WinInet
}
return FALSE;
}
#pragma once
#include <afxinet.h>
class UpLoadFile
{
public:
UpLoadFile(void);
~UpLoadFile(void);
BOOL Upload(CString strLocalFile,CString strServerIP,CString strServerPort,CString strRemoteFile);
private:
BOOL UseHttpSendReqEx(CHttpFile* httpFile,DWORD dwPostSize,CString strLocalFile);
};