fpHttpClientFormPost topic
Form Data and File Upload with fpHttpClient
Declaration
fpHttpClientFormPostDescription
The TFPHTTPClient class provides specialized methods for posting form data and uploading files.
FormPost handles URL-encoded form data, while FileFormPost uploads files using multipart/form-data encoding.
program FormPostExample;
{$mode objfpc}{$H+}
uses
SysUtils, Classes, fphttpclient, opensslsockets;
var
Client: TFPHTTPClient;
FormData: TStrings;
Response: String;
FileStream: TFileStream;
begin
Client := TFPHTTPClient.Create(nil);
FormData := TStringList.Create;
try
// Simple form post with key-value pairs
Writeln('=== Form Post Example ===');
FormData.Values['username'] := 'testuser';
FormData.Values['email'] := 'test@example.com';
FormData.Values['message'] := 'Hello from FreePascal!';
Response := Client.FormPost('https://httpbin.org/post', FormData);
Writeln('Form POST response: ', Copy(Response, 1, 150), '...');
// Form post with raw data
Writeln('=== Raw Form Data Post ===');
Response := Client.FormPost('https://httpbin.org/post', 'field1=value1&field2=value2');
Writeln('Raw form POST status: ', Client.ResponseStatusCode);
// File upload using FileFormPost
Writeln('=== File Upload Example ===');
// Create a test file to upload
FileStream := TFileStream.Create('/tmp/claude/test_upload.txt', fmCreate);
try
FileStream.WriteAnsiString('This is test content for file upload');
finally
FileStream.Free;
end;
// Upload the file
Client.FileFormPost('https://httpbin.org/post', 'file', '/tmp/claude/test_upload.txt',
TStringStream.Create(''));
Writeln('File upload status: ', Client.ResponseStatusCode);
if Client.ResponseStatusCode = 200 then
Writeln('File uploaded successfully');
// Clean up test file
if FileExists('/tmp/claude/test_upload.txt') then
DeleteFile('/tmp/claude/test_upload.txt');
finally
FormData.Free;
Client.Free;
end;
end.An experiment, built from development snapshots. Not the official Free Pascal or Lazarus documentation.
