pengjun-shanghai

根据http协议下载文件保存到相应的文件下

本实例通过提供的http网址来下载文件,并保存到本地指定的文件下。

本例提供的网址为:http://112.53.80.131:8888/database/11.mdb,下载的文件名为:11.mdb

具体代码如下:

CString sPath = m_savePath;//下载文件的保存地址
	CString m_theUrl = m_ipPath;//下载的网址
	CString filename = sPath + (_T("11.mdb"));//下载文件的保存名
	CInternetSession session;//打开链接
	CString url = m_theUrl;
	CInternetFile* file =
		(CInternetFile*)session.OpenURL(url, 1, INTERNET_FLAG_TRANSFER_BINARY);//访问地址

	if (file == NULL)
	{
		file->Close();
		delete file;
		session.Close();
		MessageBox(_T("下载文件失败! 错误代码:1"), _T("提示"), MB_ICONERROR);
		return;
	}
	CString name = filename;
	CFile file1;
	//打开保存的文件,如果该文件存在则执行重写,不存在则创建新的文件
	if (file1.Open(name, CFile::modeCreate | CFile::modeWrite | CFile::typeBinary, NULL))
	{
		//保存文件内容
		int readlen = -1;
		char buf[1024];
		while (1)
		{
			readlen = file->Read(buf, 1024);
			if (readlen == 0)
			{
				break;
			}
			file1.Write(buf, readlen);
			//delete buf;
			ZeroMemory(buf, 1024);
		}
		file1.Close();
		MessageBox(_T("下载或更新完成!"));
	}
	else
	{
		MessageBox(_T("下载文件失败! 错误代码:2"), _T("提示"), MB_ICONERROR);
		file->Close();
		delete file;
		session.Close();
		return;
	}
	//完成下载后关闭文件和链接
	file->Close();
	delete file;
	session.Close();

  

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-11-18
  • 2021-08-27
  • 2022-12-23
  • 2022-12-23
  • 2021-07-30
  • 2021-11-18
  • 2022-12-23
猜你喜欢
  • 2021-11-18
  • 2022-12-23
  • 2021-11-18
  • 2021-11-18
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案