当前位置 : 主页 > 编程语言 > delphi >

在Delphi的线程中从Internet下载文件

来源:互联网 收集:自由互联 发布时间:2021-06-23
如何在不使用Indy组件的情况下使用Delphi 2009/10中的线程从进度条下载带有进度条的文件? 这使用聪明的互联网套件来处理下载,我没有在IDE中检查它,所以我不希望它编译,毫无疑问它充满
如何在不使用Indy组件的情况下使用Delphi 2009/10中的线程从进度条下载带有进度条的文件? 这使用聪明的互联网套件来处理下载,我没有在IDE中检查它,所以我不希望它编译,毫无疑问它充满了错误,但它应该足以让你开始.

我不知道为什么你不想使用Indy,但我强烈建议让一些组件来帮助Http下载…真的没有必要重新发明轮子.

interface
type
    TMyDownloadThread= Class(TThread)
    private
        FUrl: String;
        FFileName: String;
        FProgressHandle: HWND;
        procedure GetFile (Url: String; Stream: TStream; ReceiveProgress: TclSocketProgressEvent);
        procedure OnReceiveProgress(Sender: TObject; ABytesProceed, ATotalBytes: Integer);
        procedure SetPercent(Percent: Double);
    protected
        Procedure Execute; Override;
    public
        Constructor Create(Url, FileName: String; PrograssHandle: HWND);
    End;

implementation

constructor TMyDownloadThread.Create(Url, FileName: String; PrograssHandle: HWND);
begin
    Inherited Create(True);
    FUrl:= Url;
    FFileName:= FileName;
    FProgressHandle:= PrograssHandle;
    Resume;
end;


procedure TMyDownloadThread.GetFile(Url: String; Stream: TStream; ReceiveProgress: TclSocketProgressEvent);
var
    Http: TclHttp;
begin
    Http := TclHTTP.Create(nil);
    try
        try
            Http.OnReceiveProgress := ReceiveProgress;
            Http.Get(Url, Stream);
        except
        end;
    finally
        Http.Free;
    end;
end;

procedure TMyDownloadThread.OnReceiveProgress(Sender: TObject; ABytesProceed, ATotalBytes: Integer);
begin
    SetPercent((ABytesProceed / ATotalBytes) * 100);
end;

procedure TMyDownloadThread.SetPercent(Percent: Double);
begin
    PostMessage(FProgressHandle, AM_DownloadPercent, LowBytes(Percent), HighBytes(Percent));
end;

procedure TMyDownloadThread.Execute;
var
    FileStream: TFileStream;
begin
    FileStream := TFileStream.Create(FFileName, fmCreate);
    try
        GetFile(FUrl, FileStream, OnReceiveProgress);
    finally
        FileStream.Free;
    end;        
end;
网友评论