Search code examples
delphiurlmon

Download a file with URLDownloadToFile


I use URLDownloadToFile to download a file in Delphi. In the url there is not the real name of the file. Is it possible to specify just the path of the file, keeping the default name that i.e. Explorer show?


Solution

  • You are in a catch-22 situation. You need to give URLDownloadToFile() a filename, but you have to request the URL first to discover if it has its own filename.

    You have two choices:

    1. Send a separate HEAD request to the URL first and check the Content-Disposition response header, if present. You can use HttpSendRequest() and HttpQueryInfo() for that, or any other HTTP library. You can then format a filename as needed, and then download the URL to that filename.

    2. Use a temp filename for the download, then check the Content-Disposition response header, if present, and rename the file if needed. To get the response headers from URLDownloadToFile() you have to write a class that implements the IBindStatusCallback and IHttpNegotiate COM interfaces, then pass an instance of that class to the lpfnCB parameter. The response headers will be passed to your IHttpNegotiate.OnResponse() implementation.