从FTP上面下载文件 uses WinInet, ComCtrls;function FtpDownloadFile(strHost, strUser, strPwd: string;Port: Integer; ftpDir, ftpFile, TargetFile: string; ProgressBar: TProgressBar): Boolean;function FmtFileSize(Size: Integer): string;beginif Size >= $F4240 thenResult := Format('%.2f', [Size / $F4240]) + ' Mb'elseif Size < 1000 thenResult := IntToStr(Size) + ' bytes'elseResult := Format('%.2f', [Size / 1000]) + ' Kb';end;constREAD_BUFFERSIZE = 4096; // or 256, 512, ...varhNet, hFTP, hFile: HINTERNET;buffer: array[0..READ_BUFFERSIZE - 1] of Char;bufsize, dwBytesRead, fileSize: DWORD;sRec: TWin32FindData;strStatus: string;LocalFile: file;bSuccess: Boolean;beginResult := False;{ Open an internet session }hNet := InternetOpen('Program_Name', // AgentINTERNET_OPEN_TYPE_PRECONFIG, // AccessTypenil, // ProxyNamenil, // ProxyBypass0); // or INTERNET_FLAG_ASYNC / INTERNET_FLAG_OFFLINE{Agent contains the name of the application orentity calling the Internet functions} { See if connection handle is valid }if hNet = nil thenbeginShowMessage('Unable to get access to WinInet.Dll');Exit;end;{ Connect to the FTP Server }hFTP := InternetConnect(hNet, // Handle from InternetOpenPChar(strHost), // FTP serverport, // (INTERNET_DEFAULT_FTP_PORT),PChar(StrUser), // usernamePChar(strPwd), // passwordINTERNET_SERVICE_FTP, // FTP, HTTP, or Gopher?0, // flag: 0 or INTERNET_FLAG_PASSIVE0);// User defined number for callbackif hFTP = nil thenbeginInternetCloseHandle(hNet);ShowMessage(Format('Host "%s" is not available',[strHost]));Exit;end;{ Change directory }bSuccess := FtpSetCurrentDirectory(hFTP, PChar(ftpDir));if not bSuccess thenbeginInternetCloseHandle(hFTP);InternetCloseHandle(hNet);ShowMessage(Format('Cannot set directory to %s.',[ftpDir]));Exit;end;{ Read size of file }if FtpFindFirstFile(hFTP, PChar(ftpFile), sRec, 0, 0) <> nil thenbeginfileSize := sRec.nFileSizeLow;// fileLastWritetime := sRec.lastWriteTimeend elsebeginInternetCloseHandle(hFTP);InternetCloseHandle(hNet);ShowMessage(Format('Cannot find file ',[ftpFile]));Exit;end;{ Open the file }hFile := FtpOpenFile(hFTP, // Handle to the ftp sessionPChar(ftpFile), // filenameGENERIC_READ, // dwAccessFTP_TRANSFER_TYPE_BINARY, // dwFlags0); // This is the context used for callbacks.if hFile = nil thenbeginInternetCloseHandle(hFTP);InternetCloseHandle(hNet);Exit;end;{ Create a new local file }AssignFile(LocalFile, TargetFile);{$i-}Rewrite(LocalFile, 1);{$i+}if IOResult <> 0 thenbeginInternetCloseHandle(hFile);InternetCloseHandle(hFTP);InternetCloseHandle(hNet);Exit;end;dwBytesRead := 0;bufsize := READ_BUFFERSIZE;while (bufsize > 0) dobeginApplication.ProcessMessages;if not InternetReadFile(hFile,@buffer, // address of a buffer that receives the dataREAD_BUFFERSIZE, // number of bytes to read from the filebufsize) then Break; // receives the actual number of bytes readif (bufsize > 0) and (bufsize <= READ_BUFFERSIZE) thenBlockWrite(LocalFile, buffer, bufsize);dwBytesRead := dwBytesRead + bufsize;{ Show Progress }ProgressBar.Position := Round(dwBytesRead * 100 / fileSize);Form1.Label1.Caption := Format('%s of %s / %d %%',[FmtFileSize(dwBytesRead),FmtFileSize(fileSize) ,ProgressBar.Position]);end;CloseFile(LocalFile);InternetCloseHandle(hFile);InternetCloseHandle(hFTP);InternetCloseHandle(hNet);Result := True;end;
http://expert.csdn.net/Expert/topic/1806/1806565.xml?temp=.6055719
和
http://expert.csdn.net/Expert/topic/1763/1763783.xml?temp=.9343378
学习ing^^^^……
uses
WinInet, ComCtrls;function FtpDownloadFile(strHost, strUser, strPwd: string;Port: Integer; ftpDir, ftpFile, TargetFile: string; ProgressBar: TProgressBar): Boolean;function FmtFileSize(Size: Integer): string;beginif Size >= $F4240 thenResult := Format('%.2f', [Size / $F4240]) + ' Mb'elseif Size < 1000 thenResult := IntToStr(Size) + ' bytes'elseResult := Format('%.2f', [Size / 1000]) + ' Kb';end;constREAD_BUFFERSIZE = 4096; // or 256, 512, ...varhNet, hFTP, hFile: HINTERNET;buffer: array[0..READ_BUFFERSIZE - 1] of Char;bufsize, dwBytesRead, fileSize: DWORD;sRec: TWin32FindData;strStatus: string;LocalFile: file;bSuccess: Boolean;beginResult := False;{ Open an internet session }hNet := InternetOpen('Program_Name', // AgentINTERNET_OPEN_TYPE_PRECONFIG, // AccessTypenil, // ProxyNamenil, // ProxyBypass0); // or INTERNET_FLAG_ASYNC / INTERNET_FLAG_OFFLINE{Agent contains the name of the application orentity calling the Internet functions} { See if connection handle is valid }if hNet = nil thenbeginShowMessage('Unable to get access to WinInet.Dll');Exit;end;{ Connect to the FTP Server }hFTP := InternetConnect(hNet, // Handle from InternetOpenPChar(strHost), // FTP serverport, // (INTERNET_DEFAULT_FTP_PORT),PChar(StrUser), // usernamePChar(strPwd), // passwordINTERNET_SERVICE_FTP, // FTP, HTTP, or Gopher?0, // flag: 0 or INTERNET_FLAG_PASSIVE0);// User defined number for callbackif hFTP = nil thenbeginInternetCloseHandle(hNet);ShowMessage(Format('Host "%s" is not available',[strHost]));Exit;end;{ Change directory }bSuccess := FtpSetCurrentDirectory(hFTP, PChar(ftpDir));if not bSuccess thenbeginInternetCloseHandle(hFTP);InternetCloseHandle(hNet);ShowMessage(Format('Cannot set directory to %s.',[ftpDir]));Exit;end;{ Read size of file }if FtpFindFirstFile(hFTP, PChar(ftpFile), sRec, 0, 0) <> nil thenbeginfileSize := sRec.nFileSizeLow;// fileLastWritetime := sRec.lastWriteTimeend elsebeginInternetCloseHandle(hFTP);InternetCloseHandle(hNet);ShowMessage(Format('Cannot find file ',[ftpFile]));Exit;end;{ Open the file }hFile := FtpOpenFile(hFTP, // Handle to the ftp sessionPChar(ftpFile), // filenameGENERIC_READ, // dwAccessFTP_TRANSFER_TYPE_BINARY, // dwFlags0); // This is the context used for callbacks.if hFile = nil thenbeginInternetCloseHandle(hFTP);InternetCloseHandle(hNet);Exit;end;{ Create a new local file }AssignFile(LocalFile, TargetFile);{$i-}Rewrite(LocalFile, 1);{$i+}if IOResult <> 0 thenbeginInternetCloseHandle(hFile);InternetCloseHandle(hFTP);InternetCloseHandle(hNet);Exit;end;dwBytesRead := 0;bufsize := READ_BUFFERSIZE;while (bufsize > 0) dobeginApplication.ProcessMessages;if not InternetReadFile(hFile,@buffer, // address of a buffer that receives the dataREAD_BUFFERSIZE, // number of bytes to read from the filebufsize) then Break; // receives the actual number of bytes readif (bufsize > 0) and (bufsize <= READ_BUFFERSIZE) thenBlockWrite(LocalFile, buffer, bufsize);dwBytesRead := dwBytesRead + bufsize;{ Show Progress }ProgressBar.Position := Round(dwBytesRead * 100 / fileSize);Form1.Label1.Caption := Format('%s of %s / %d %%',[FmtFileSize(dwBytesRead),FmtFileSize(fileSize) ,ProgressBar.Position]);end;CloseFile(LocalFile);InternetCloseHandle(hFile);InternetCloseHandle(hFTP);InternetCloseHandle(hNet);Result := True;end;
代码如下
unit Unit1;interfaceuses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ComCtrls, StdCtrls, Psock, NMHttp, ExtCtrls, jpeg;type
TfrmDownload = class(TForm)
NMHTTP1: TNMHTTP;
btnGet: TButton;
Label1: TLabel;
edtURL: TEdit;
StatusBar1: TStatusBar;
Label2: TLabel;
tempFileName: TLabel;
Label4: TLabel;
finalFileName: TLabel;
ProgressBar1: TProgressBar;
btnExit: TButton;
procedure btnGetClick(Sender: TObject);
procedure NMHTTP1Success(Cmd: CmdType);
procedure FormCreate(Sender: TObject);
procedure NMHTTP1Failure(Cmd: CmdType);
procedure NMHTTP1PacketRecvd(Sender: TObject);
procedure btnExitClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmDownload: TfrmDownload;
implementation
{$R *.DFM}procedure TfrmDownload.btnGetClick(Sender: TObject);
begin
NMHTTP1.Get(edtURL.text);
// 下载URL指定的文件
end;procedure TfrmDownload.NMHTTP1Success(Cmd: CmdType);
var
filName:string;
buf:string;
pnewfile,poldfile:pchar;
i:integer;
begin
// 获取临时文件名
filName:=nmhttp1.body;
// 获取文件名
for i:=length(edtURL.Text) downto 1 do
if edtURL.text[i]<>'/' then
buf:=edtURL.text[i]+buf // 获取URL所指文件名
else
break;
// 获取下载的临时文件指针
Getmem(poldFile,length(filName)+1);
StrPCopy(poldFile,filName);
// 为URL所指文件分配内存
Getmem(pnewfile,length(buf)+1);
StrPCopy(pnewfile,buf);
// 将下载文件名重命名为URL所指文件名
MoveFile(poldfile,pnewfile);
// 释放文件指针所指的内存
Freemem(poldfile);
Freemem(pnewfile);
// 显示相关信息
statusbar1.Panels.Items[0].text:='下载完成';
tempFileName.caption:= filName;
finalFileName.Caption:=buf;
end;procedure TfrmDownload.FormCreate(Sender: TObject);
begin
//保存获得的文件
NMHTTP1.InputFileMode:= TRUE;
NMHTTP1.TimeOut:=2000;
//设置临时文件名
NMHTTP1.Body:='tempFile';
NMHTTP1.Header:='HeaderFile';
// 初始化进度条
ProgressBar1.Min:=0;
ProgressBar1.Max:=100;
ProgressBar1.Position:=0;
end;procedure TfrmDownload.NMHTTP1Failure(Cmd: CmdType);
begin
StatusBar1.Panels.Items[0].text:='操作失败';
end;procedure TfrmDownload.NMHTTP1PacketRecvd(Sender: TObject);
begin
// 显示下载进度
ProgressBar1.Position :=
Round( NMHTTP1.BytesRecvd /NMHTTP1.BytesTotal)*100;
end;procedure TfrmDownload.btnExitClick(Sender: TObject);
begin
frmDownload.Close;
end;end.