#include <windows.h>
#include"down.h"
#include <urlmon.h>
#include <tchar.h>
#include <string>
#include <iostream>
using namespace std;
#pragma comment(lib,"urlmon.lib")
#pragma comment(lib,"ws2_32.lib")
#void down(string url, string SavePath);
void down(string url, string savepath)
{
/* time_t lt;
lt = time(NULL);
url = url + "?" + to_string(lt);*/
size_t len = url.length();//获取字符串长度
int nmlen = MultiByteToWideChar(CP_ACP, 0, url.c_str(), len + 1, NULL, 0);//如果函数运行成功,并且cchWideChar为零,
//返回值是接收到待转换字符串的缓冲区所需求的宽字符数大小。
wchar_t* buffer = new wchar_t[nmlen];
MultiByteToWideChar(CP_ACP, 0, url.c_str(), len + 1, buffer, nmlen);
//DeleteUrlCacheEntry(imgsavepath);
DeleteUrlCacheEntry(buffer);
HRESULT hr = URLDownloadToFile(NULL, buffer, _T(".\\temp\\0.jpg"), 0, NULL);
if (hr == S_OK)
{
cout << "-------下载完成---------------------" << endl;
}
else
{
cout << "---------------图片下载失败---------------------------" << endl;
}
}
上面的方法存在一个致命问题就是占用磁盘增加,导致最后磁盘爆满,后面采用了另外一种方法
void download(const char* Url, const char* save_as)
{
byte Temp[MAXBLOCKSIZE];
ULONG Number = 1;
FILE* stream;
HINTERNET hSession = InternetOpen("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(save_as, "wb")) != NULL)
{
while (Number > 0)
{
InternetReadFile(handle2, Temp, MAXBLOCKSIZE - 1, &Number);
fwrite(Temp, sizeof(char), Number, stream);
}
fclose(stream);
}
InternetCloseHandle(handle2);
handle2 = NULL;
}
InternetCloseHandle(hSession);
hSession = NULL;
}
}