2
votes

I am new with indy servers and so I'm struggling for this simple task. I have to create a server and upload a little file; its size is always 128 bytes. Then when someone opens the homepage of the server the file is sent automatically. So:

  1. Upload a file (the one that is 128 bytes) on the disk
  2. Open a browser like Firefox
  3. Type the url (below you can see that I've set 127.0.0.1:798) and when you press enter there is a white page but a dialog appears asking you to download the file.

I have written this code so far:

procedure TForm1.Button1Click(Sender: TObject);
begin

 // IP = 127.0.0.1:798 (port is 798)
 IdTCPServer1.Active := true;
 Memo1.Lines.Add('Server started at: ' + TimeToStr(Now) + slinebreak);

end;

procedure TForm1.Button2Click(Sender: TObject);
begin

 IdTCPServer1.Active := false;
 Memo1.Lines.Add('Server stopped at: ' + TimeToStr(Now));

end;

procedure TForm1.IdTCPServer1Execute(AContext: TIdContext);
var a: TFileStream;

begin

  a := TFileStream.Create('C:\Users\defaulr.user\Desktop\datfile.pkm', fmOpenWrite);
  AContext.Connection.IOHandler.Write(a);

end;

This is the form:

enter image description here

Start is Button1 and End is Button2. As you can see I am loading in a stream the file and then I try to send it as output when I open the page. Is this the proper way to do it?

1
Just a minor nitpick: if you would give meaningful names to the components, you would not have to explain what Button1 etc. are. E.g. StartBtn and StopBtn.Tom Brunberg
And also you should use try-finally and/or try-catch blocksAlberto Miola

1 Answers

3
votes

Since you are accessing the file via a web browser, you should be using TIdHTTPServer instead of TIdTCPServer:

procedure TForm1.Button1Click(Sender: TObject);
begin
  // IP = 127.0.0.1:798 (port is 798)
  IdHTTPServer1.Active := true;
  Memo1.Lines.Add('Server started at: ' + TimeToStr(Now));
end;

procedure TForm1.Button2Click(Sender: TObject);
begin
  IdHTTPServer1.Active := false;
  Memo1.Lines.Add('Server stopped at: ' + TimeToStr(Now));
end;

// TIdHTTPServer.OnCommandGet event handler...
procedure TForm1.IdHTTPServer1CommandGet(AContext: TIdContext;
  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
begin
  if ARequestInfo.Document = '/' then
  begin
    AResponseInfo.ResponseNo := 200;
    AResponseInfo.ServeFile(AContext, 'C:\Users\defaulr.user\Desktop\datfile.pkm');
    // alternatively:
    // AResponseInfo.SmartServeFile(AContext, ARequestInfo, 'C:\Users\defaulr.user\Desktop\datfile.pkm');
  end else
    AResponseInfo.ResponseNo := 404;
end;