#include "stdafx.h"
#include "Upload.h"
#include "utils.h"
#include <wininet.h>
#include <afxinet.h>

CString CUpload::mErrMsg;

static BOOL UploadFile(LPCTSTR strURL, LPCTSTR strLocalFileName);

CUpload::CUpload(void)
{
}

CUpload::~CUpload(void)
{
}

BOOL CUpload::upload(CString& path, CString& name, CString& idCard)
{
	return util_upload(name, idCard, path);
}

CString& CUpload::getErrMsg()
{
	return mErrMsg;
}

BOOL UploadFile(LPCTSTR strURL, LPCTSTR strLocalFileName)
{
	ASSERT(strURL != NULL && strLocalFileName != NULL);
	BOOL bResult = FALSE;
	DWORD dwType = 0;
	CString strServer;
	CString strObject;
	INTERNET_PORT wPort = 0;
	DWORD dwFileLength = 0;
	char * pFileBuff = NULL;
	CHttpConnection * pHC = NULL;
	CHttpFile * pHF = NULL;
	CInternetSession cis;
	bResult =  AfxParseURL(strURL, dwType, strServer, strObject, wPort);
	if(!bResult)
		return FALSE;
	CFile file;
	try
	{
		if(!file.Open(strLocalFileName, CFile::shareDenyNone | CFile::modeRead))
			return FALSE;
		dwFileLength = file.GetLength();
		if(dwFileLength <= 0)
			return FALSE;
		pFileBuff = new char[dwFileLength];
		memset(pFileBuff, 0, sizeof(char) * dwFileLength);
		file.Read(pFileBuff, dwFileLength);
		const int nTimeOut = 5000;
		cis.SetOption(INTERNET_OPTION_CONNECT_TIMEOUT, nTimeOut); //联接超时设置
		cis.SetOption(INTERNET_OPTION_CONNECT_RETRIES, 1);  //重试1次
		pHC = cis.GetHttpConnection(strServer, wPort);  //取得一个Http联接
		pHF = pHC->OpenRequest(CHttpConnection::HTTP_VERB_POST, strObject);
		if(!pHF->SendRequest(NULL, 0, pFileBuff, dwFileLength))
		{
			delete[]pFileBuff;
			pFileBuff = NULL;
			pHF->Close();
			pHC->Close();
			cis.Close();
			return FALSE;
		}
		DWORD dwStateCode = 0;
		pHF->QueryInfoStatusCode(dwStateCode);
		if(dwStateCode == HTTP_STATUS_OK)
			bResult = TRUE;
	}
	catch(CInternetException * pEx)
	{
		TCHAR sz[256] = _T("");
		pEx->GetErrorMessage(sz, 25);
		AfxMessageBox(CString(sz));
	}
	catch(CFileException& fe)
	{
		CString str;
		str.Format(L"FileException occur!\r\n%d", fe.m_lOsError);
		AfxMessageBox(str);
	}
	catch(...)
	{
		ShowErrBox(GetLastError());
	}

	delete[]pFileBuff;
	pFileBuff = NULL;
	file.Close();
	pHF->Close();
	pHC->Close();
	cis.Close();

	return bResult;
}
