本文整理自网络,侵删。
一、URLDownloadToFile()函数介绍使用微软提供的URLDownloadToFile function函数,函数原型:
HRESULT URLDownloadToFile( LPUNKNOWN pCaller, LPCTSTR szURL, LPCTSTR szFileName, _Reserved_ DWORD dwReserved, LPBINDSTATUSCALLBACK lpfnCB);
该函数支持http,https协议的网站文件下载,使用简单。微软件官方参考文档:
https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/ms775123(v=vs.85)
二、delphi下对URLDownloadToFile()函数的封装//uses urlmon;function DownloadToFile(Source, Dest: string): Boolean;begin try Result := UrlDownloadToFile(nil, PChar(source), PChar(Dest), 0, nil) = 0; except Result := False; end;end;
使用该函数需要注意几点:
url链接必须带上http://或https://头部;本地路径为文件的绝对路径;需要引入单元文件:uses urlmon;该函数运行时会阻塞主线程,因此最好放到子线程内运行;使用该函数下载文件比IdHTTP控件简单易用,IdHTTP控件对https协议支持不好;三、使用示例1.主线程中使用:
DownloadToFile("https://www.w3school.com.cn/html/html_elements.asp","c:\html_elements.asp");
2.子线程中使用:
//uses urlmon;function DownloadToFile(Source, Dest: string): Boolean;begin try Result := UrlDownloadToFile(nil, PChar(source), PChar(Dest), 0, nil) = 0; except Result := False; end;end;
function ThreadProc(param: LPVOID): DWORD; stdcall;begin DownloadToFile("https://www.w3school.com.cn/html/html_elements.asp","c:\html_elements.asp"); Result := 0;end;
procedure downloadFilesThread();var threadId: TThreadID;begin bDownFiles:=true; CreateThread(nil, 0, @ThreadProc, nil, 0, threadId);end;
相关阅读 >>
更多相关阅读请进入《Delphi》频道 >>