Delphi将文件上传到FTP

时间:2015-12-27 13:28:59

标签: delphi text ftp

我刚创建了这个小应用程序,它将2个字符串转储到txt文件中。现在我希望将txt文件上传到ftp。我看了一些教程,但找不到任何关于如何做的好教程。请帮我。我发布了我的代码文件。

   var

  fText:textfile;
  sText:string;
  s1Text:string;
begin
assignfile(fText,'d:\test.txt') ;

if fileExists('d:\test.txt') <>true then
begin

  rewrite(fText);
  end

  else
  begin
  Append(fText)
  end;


  sText:=Edit1.Text;
  s1Text:=Edit2.Text;
  writeln(fText,sText) ;
  writeln(fText,s1Text);
  closefile(fText);
end;

1 个答案:

答案 0 :(得分:-1)

一种方法是通过使用CreateProcess在您的Delphi代码中调用的Windows FTP命令。为了便于扩展上传更多文件的功能,我使用了一个上传脚本来告诉Windows FTP命令该怎么做。 (类似的功能可用于下载文件:首先将put更改为get

function TForm1.Upload: Boolean;
var
  Script: TStringList;
  Command: String;
begin

    Script := TStringList.Create;
    try
      Script.Text := 'User Username' + #13#10 +
      'Password' + #13#10 +
      'cd /temp' + #13#10 + // ftp folder (destination)
      'put d:\test.txt' + #13#10 + // local folder (source)
      'bye';
      Script.SaveToFile('d:\test\myuploadscript.txt');

      Command := 'FTP -v -i -n -s:"d:\test\myuploadscript.txt" ftp://mytestftpsite'

      Result := ExecNewProcess(Command, True);

   finally
     Script.Free;
   end;

end;

function TForm1.ExecNewProcess(ProgramName: String; AShowMsg: Boolean): Longword;
var
  StartInfo: TStartupInfo;
  ProcInfo: TProcessInformation;
  CreateOK: Boolean;
begin

  FillChar(StartInfo,SizeOf(TStartupInfo),#0);
  FillChar(ProcInfo,SizeOf(TProcessInformation),#0);
  StartInfo.cb := SizeOf(TStartupInfo);
  if AShowMsg then
  begin
    StartInfo.dwFlags := STARTF_USESHOWWINDOW;
    StartInfo.wShowWindow := SW_SHOW;
  end;

  CreateOK := CreateProcess(nil, @ProgramName[1], nil, nil, False,
              NORMAL_PRIORITY_CLASS,
              nil, nil, StartInfo, ProcInfo);

  if CreateOK then
  begin
    WaitForSingleObject(ProcInfo.hProcess, INFINITE);
    GetExitCodeProcess(ProcInfo.hProcess, Result);
  end;

  if ProcInfo.hProcess <> 0 then
    CloseHandle(ProcInfo.hProcess);
  if ProcInfo.hThread <> 0 then
    CloseHandle(ProcInfo.hThread);
end;