VC++下载文件获取进度示例

作者:袖梨 2022-06-25
 代码如下 复制代码

//获取当前时间戳
int GetUnixTime()
{
 CTime time = CTime::GetCurrentTime();
 return (int)time.GetTime();
}


CString FormatUnit(double nBytes)
{
 char* units[5] = {"B", "KB", "MB", "GB", "TB"};
 int i;
 for (i = 0; ((int)nBytes) >= 1024 && i < 4; i++)
  nBytes /= 1024;
 CString strResult;
 strResult.Format("%.2f%s", nBytes, units[i]);
 return strResult;
}

DWORD WINAPI DownloadFile(LPVOID pParam)
{
 CInstallOnlineDlg* pWnd = (CInstallOnlineDlg*)AfxGetApp()->m_pMainWnd;
 char                filebuf[512];
 CInternetSession    netSession;
 CStdioFile          *fTargFile = NULL;
 CString             szFile(DOWNLOAD_URL), FileSize, KBin, KBsec, NewName, Perc, strLeft, strRight;
 int nDownloaded = 1;
 try
 {
  pWnd->SetLeftString("正在校验下载地址...");
  fTargFile = netSession.OpenURL(szFile, 1, INTERNET_FLAG_TRANSFER_BINARY | INTERNET_FLAG_RELOAD);
  int filesize = fTargFile->SeekToEnd();
  fTargFile->SeekToBegin();

  // 在当前目录创建新的目标文件 
  CFile fDestFile(fTargFile->GetFileName(), CFile::modeCreate | CFile::modeWrite | CFile::typeBinary);
  int byteswrite;     // 写入文件的字节数 
  int pos = 0;        // 当前进度条的位置 
  double kbsec;  // 记录秒数, 速度(KB/秒) 
  int secs;
 
  pWnd->SetFileName(fTargFile->GetFileName());
  pWnd->m_progress.SetRange32(0, filesize);

  int nStartTime = GetUnixTime();
  int nLastOutputTime = 0;
  CString strFileSize = FormatUnit(filesize);
  while (byteswrite = fTargFile->Read(filebuf, 512))   // 读取文件 
  {
   // 根据开始时间与当前时间比较,获取秒数
   int nCurrentTime = GetUnixTime();
   secs = nCurrentTime - nStartTime;
   secs = secs == 0 ? 1 : secs;
   pos = pos + byteswrite;                 // 设置新的进度条位置 
   fDestFile.Write(filebuf, byteswrite);   // 将实际数据写入文件 
   pWnd->m_progress.SetPos(pos);

   if ((nCurrentTime - nLastOutputTime) > 1)
   {
    kbsec = pos / secs;                  // 获取每秒下载多少(KB)
    CString strRecv = FormatUnit(pos);
    CString strSpeed = FormatUnit(kbsec);
    strLeft.Format("下载进度:%s/%s", strRecv.GetBuffer(), strFileSize.GetBuffer());
    pWnd->SetLeftString(strLeft);
    strRight.Format("下载速度:%s/s", strSpeed.GetBuffer());
    pWnd->SetRightString(strRight);
    nLastOutputTime = nCurrentTime;
   }
  }
  // 下载完成,关闭文件 
  fDestFile.Close();
 }

 catch (CInternetException *IE)
 {
  CString strerror;
  TCHAR error[255];

  IE->GetErrorMessage(error, 255); // 获取错误消息 
  strerror = error;

  pWnd->SetLeftString(strerror);
  pWnd->SetRightString("");
  if (fTargFile)
   delete fTargFile;
  IE->Delete();                    // 删除异常对象,以防止泄漏 
  pWnd->SetDownloadStatus(FALSE);
  pWnd->GetDlgItem(IDC_BUTTON1)->EnableWindow(TRUE);
  return 0;
 }
 if (fTargFile)
  delete fTargFile;
 if (nDownloaded == 1)
 {
  pWnd->SetLeftString("下载完成,请单击“安装”!");
  pWnd->m_btn.LoadBitmaps(IDB_BTN_INSTALL_NORMAL);
  pWnd->m_btn.SizeToContent();
  pWnd->SetDownloadStatus(TRUE);
  pWnd->GetDlgItem(IDC_BUTTON1)->EnableWindow(TRUE);
 }
 return 0;
}

相关文章

精彩推荐