Controlling file downloads

后端 未结 2 527
感情败类
感情败类 2021-01-07 03:43

I am building an updater for my program with the use of a TWebBrowser. OnCreate the TWebBrowser navigates to the given URL. To download the update, the user is required to c

相关标签:
2条回答
  • 2021-01-07 04:17

    TWebBrowser isn't what you want since you aren't displaying active HTML content. As was said before, there are numerous other options. Basically you want a HTTP request.

    Here's a very simple example using WinInet, which will need to be adapted to your needs (threading, status messages and so-on).

    function DownloadURL(inURL, destfile: string): boolean;
      var
        hOpen: HINTERNET;
        hFile: HINTERNET;
        myAgent: string;
        savefile: file;
        amount_read: integer;
       // the buffer size here generally reflects maximum MTU size.
       // for efficiency sake, you don't want to use much more than this.
        mybuffer: array[1..1460] of byte;
      begin
        Result := true;
        myAgent := 'Test downloader app';
       // other stuff in this call has to do with proxies, no way for me to test
        hOpen := InternetOpen(PChar(myAgent), 0, nil, nil, 0);
        if hOpen = nil then
          begin
            Result := false;
            exit;
          end;
        try
          hFile := InternetOpenURL(hOpen, PChar(inURL), nil, 0,
               INTERNET_FLAG_RELOAD or INTERNET_FLAG_DONT_CACHE, 0);
          if hFile = nil then
            begin
              Result := false;
              exit;
            end;
          try
            AssignFile(savefile, destfile);
            Rewrite(savefile, 1);
            InternetReadFile(hFile, @myBuffer, sizeof(mybuffer), amount_read);
            repeat
              Blockwrite(savefile, mybuffer, amount_read);
              InternetReadFile(hFile, @myBuffer, sizeof(mybuffer), amount_read);
            until amount_read = 0;
            CloseFile(savefile);
          finally
            InternetCloseHandle(hFile);
          end;
        finally
          InternetCloseHandle(hOpen);
        end;
      end;
    
    procedure TForm1.Button1Click(Sender: TObject);
      // example usage.
      begin
        if SaveDialog1.Execute then
          begin
            if DownloadURL(Edit1.Text, SaveDialog1.FileName) then
              ShowMessage('file downloaded.')
            else
              ShowMessage('Error downloading file.');
          end;
      end;
    
    0 讨论(0)
  • 2021-01-07 04:24

    I would use Indy's TIdHTTP component for that, eg:

    uses
      ..., IdHTTP;
    
    var
      Url, LocalFile: String;
      Strm: TFileStream;
    begin
      Url := ...;
      LocalFile := ...;
      Strm := TFileStream.Create(LocalFile, fmCreate);
      try
        try
          IdHTTP.Get(Url, Strm);
        finally
          Strm.Free;
        end;
      except
        DeleteFile(LocalFile);
        raise;
      end;
    end;
    
    0 讨论(0)
提交回复
热议问题