|
此方法依赖wininet.lib
属性 - 配置属性 - 链接器 - 输入 - 附加依赖项 - 编辑
实现代码如下
#include "WinInet.h"
#define MAXBLOCKSIZE 1024
/*!
* @brief 下载一个文件到本地计算机
*
* @param const CString& url 文件链接
* @param const CString& savePath 文件保存到本地计算机的文件夹路径
*
* @return bool 下载成功返回true
*
* @author 刘杰达
*/
bool Application::downloadFileToLocal(const CString& url, const CString& savePath)
{
bool ret = false;
byte Temp[1024];
ULONG Number = 1;
char * szSavePath = CStringtochar(savePath);
FILE *stream;
HINTERNET hSession = InternetOpen(L"RookIE/1.0", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if (hSession != NULL)
{
HINTERNET handle2 = InternetOpenUrl(hSession, url, NULL, 0, INTERNET_FLAG_DONT_CACHE, 0);
if (handle2 != NULL)
{
if ((stream = fopen(szSavePath, "wb")) != NULL)
{
while (Number > 0)
{
InternetReadFile(handle2, Temp, MAXBLOCKSIZE - 1, &Number);
fwrite(Temp, sizeof(char), Number, stream);
}
fclose(stream);
ret = true;
}
InternetCloseHandle(handle2);
handle2 = NULL;
}
InternetCloseHandle(hSession);
hSession = NULL;
}
if (szSavePath != NULL)
{
delete[] szSavePath;
}
return ret;
}
char *CStringtochar(CString str)
{
char *ptr;
#ifdef _UNICODE
LONG len;
len = WideCharToMultiByte(CP_ACP, 0, str, -1, NULL, 0, NULL, NULL);
ptr = new char[len + 1]; memset(ptr, 0, len + 1);
WideCharToMultiByte(CP_ACP, 0, str, -1, ptr, len + 1, NULL, NULL);
#else
ptr = new char[str.GetAllocLength() + 1];
sprintf(ptr, _T("%s"), str);
#endif
return ptr;
}
|
|