Save a file downloaded via WinHTTP to disk, using Delphi XE

拥有回忆 提交于 2019-11-30 15:44:10

Warren, you must use the AxCtrls.TOleStream class to comunicate the response stream with the Classes.TFileStream

something like this

IWinHttpRequest.ResponseStream -> TOleStream -> TFileStream

Check this sample code

{$APPTYPE CONSOLE}

uses
  Variants,
  ActiveX,
  Classes,
  AxCtrls,
  WinHttp_TLB,
  SysUtils;


function Download(const url, filename: String): Boolean;
var
   http: IWinHttpRequest;
   wUrl: WideString;
   fs:TFileStream;
   HttpStream :IStream;
   sz,rd,wr:Int64;
   FStatus : Integer;
   OleStream: TOleStream;
begin
  try
   wUrl := url;
   http := CoWinHttpRequest.Create;
   http.open('GET', wurl, False);
   http.send(EmptyParam);

   FStatus := http.status; // 200=OK!
   result := FStatus=200;

   if result then
   begin
    HttpStream:=IUnknown(http.ResponseStream) as IStream;
    OleStream:= TOleStream.Create(HttpStream);
    try
      fs:= TFileStream.Create(FileName, fmCreate);
      try
        OleStream.Position:= 0;
        fs.CopyFrom(OleStream, OleStream.Size);
      finally
        fs.Free;
      end;
    finally
      OleStream.Free;
    end;
   end;

  except
      result := false;
      // do not raise exceptions.
  end;
end;


begin
  try
    Download('http://foo.html','C:\Foo\anyfile.foo');
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!