CHttpFile实现下载文件
CString sFileName = "abc.exe";
CString strFilePath;
CFileDialog fileDlg(FALSE, "exe", sFileName,OFN_OVERWRITEPROMPT|OFN_HIDEREADONLY);
fileDlg.m_ofn.lpstrTitle = "保存文件";
fileDlg.m_ofn.lpstrFilter = "All Files(*.*)\0*.*\0\0";
if(IDOK == fileDlg.DoModal())
{
strFilePath = fileDlg.GetFolderPath();
strFilePath += fileDlg.GetFileName();
CString strFileName="http://localhost/" + sFileName;
CInternetSession sess;
CHttpFile* pHttpFile;
try
{
pHttpFile=(CHttpFile*)sess.OpenURL(strFileName);
}
catch(CException* e)
{
pHttpFile = 0;
throw;
}
if(pHttpFile)
{
DWORD dwStatus;
DWORD dwBuffLen = sizeof(dwStatus);
BOOL bSuccess = pHttpFile->QueryInfo(HTTP_QUERY_STATUS_CODE|HTTP_QUERY_FLAG_NUMBER, &dwStatus, &dwBuffLen);
char strarray[1024];
if( bSuccess && dwStatus>= 200&& dwStatus<300 )
{
CFile NetFile;
DWORD dwFileLen = 0,dwIndex = 0;
dwFileLen = pHttpFile->SeekToEnd();
pHttpFile->SeekToBegin();
if(NetFile.Open(sFileName, CFile::modeWrite|CFile::modeCreate))
{
int nCount = 0;
while(dwIndex<dwFileLen)
{
nCount = pHttpFile->Read(strarray,1023);
NetFile.Write(strarray,nCount);
dwIndex += nCount;
}
NetFile.Close();
AfxMessageBox("下载完毕");
}
else
{
AfxMessageBox("本地文件"+sFileName+"打开出错.");
}
}
else
{
CString strSentence;
strSentence.Format("打开网页文件出错,错误码:%d", dwStatus);
AfxMessageBox(strSentence);
}
pHttpFile->Close();
delete pHttpFile;
}
else
AfxMessageBox("不能找到网页文件!");
sess.Close();
execv(strFilePath.GetBuffer(), NULL);
}
转自:http://hi.baidu.com/songshu5555/blog/item/40cc51d10ba6c2c9572c84b6.html