利用TIdHttp实现文件下载的分块断点续传

环境delphi2007 + indy

网上有大量利用TIdHttp控件下载并支持断点续传的例子,但在delphi2007环境下运行都不成功。最近应为项目需要编写了一个测试程序,可以成功实现分块断点续传,并支持链接重定向后,自动获得真实的下载文件名。供大家参考。

(想修改成多线程下载也只是增加一些逻辑就可以了。)

procedure TForm3.RzButton1Click(Sender: TObject); var IdHttp: TIdHttp; MemStream: TMemoryStream; UrlStr, DFileName: string; FilePosition: int64; FileSize: integer; begin //初始化进度条 RzProgressBar1.TotalParts := 0; RzProgressBar1.PartsComplete := 0; //获取下载地址 UrlStr := trim(RzEditUrl.Text); IdHttp := tIdHttp.Create(nil); IdHttp.ProtocolVersion := pv1_1 ; //IdHttp.RecvBufferSize := 1024 ; IdHttp.HandleRedirects := true; try //获取重定向后的下载地址和文件大小 IdHttp.Head(UrlStr); FileSize := IdHttp.Response.ContentLength; DFileName := idhttp.URL.URI; //由下载地址转换为保存文件名 while pos('/',DFileName) > 0 do begin delete(DFileName, 1, pos('/',DFileName)); end; while pos('/',DFileName) > 0 do begin delete(DFileName, 1, pos('/',DFileName)); end; if DFileName = '' then exit; FilePosition := 0; MemStream := TMemoryStream.Create; if FileExists(ExtractFilePath(Application.ExeName) + DFileName) then begin try MemStream.LoadFromFile(ExtractFilePath(Application.ExeName) + DFileName); MemStream.Seek(0, soFromEnd); FilePosition := MemStream.Size; except MemStream.Free; RzMemo1.lines.Add(Format('Open file "%S" failed!', [DFileName])); exit; end; end; //初始化进度条 RzProgressBar1.TotalParts := FileSize; RzProgressBar1.PartsComplete := FilePosition; RzMemo1.Lines.Add('FileName:' + DFileName); RzMemo1.Lines.Add('FileSize:' + IntToStr(RzProgressBar1.TotalParts)); while FilePosition < FileSize do begin //方法1:未验证 //IdHttp.Request.ContentRangeStart := FilePosition; //IdHttp.Request.ContentRangeEnd := FilePosition + 1024; //方法2:已验证 IdHttp.Request.Range := IntToStr(FilePosition) + '-' ; if FilePosition + 10240 < FileSize then IdHttp.Request.Range := IdHttp.Request.Range + IntToStr(FilePosition + 10239); IdHttp.get(idhttp.URL.URI, MemStream); //MemStream.LoadFromStream(IdHttp.Response.ContentStream); MemStream.SaveToFile(ExtractFilePath(Application.ExeName) + DFileName); FilePosition := MemStream.Size; //刷新进度条 RzProgressBar1.PartsComplete := FilePosition; Application.ProcessMessages; //sleep(50); //为确保能够看到下载过程,添加此延时 end; finally IdHttp.Free; MemStream.Free; end; end;

你可能感兴趣的:(Delphi,Lazarus,+,FreePascal)