fpHttpClientFileUpload topic
File Upload with Local Filename
Declaration
fpHttpClientFileUploadDescription
The FileFormPost method provides an easy way to upload local files to a server.
It automatically handles multipart/form-data encoding and sets appropriate headers.
The method takes the URL, form field name, local filename, and a response stream.
program FileUploadExample;
{$mode objfpc}{$H+}
uses
SysUtils, Classes, fphttpclient, opensslsockets;
procedure CreateTestFile(const FileName: String);
var
F: TextFile;
begin
AssignFile(F, FileName);
Rewrite(F);
try
Writeln(F, 'Sample file content for upload test');
Writeln(F, 'Created: ', DateTimeToStr(Now));
Writeln(F, 'This file will be uploaded via HTTP POST');
finally
CloseFile(F);
end;
end;
var
Client: TFPHTTPClient;
ResponseStream: TStringStream;
TestFileName: String;
begin
Client := TFPHTTPClient.Create(nil);
ResponseStream := TStringStream.Create('');
TestFileName := '/tmp/claude/upload_test.txt';
try
// Create a test file to upload
CreateTestFile(TestFileName);
Writeln('=== File Upload with Local Filename ===');
Writeln('Uploading file: ', TestFileName);
// Configure client for file upload
Client.AllowRedirect := True;
Client.AddHeader('User-Agent', 'FreePascal-FileUploader/1.0');
// Upload the file
// Parameters: URL, field name, local filename, response stream
Client.FileFormPost('https://httpbin.org/post', 'uploaded_file', TestFileName, ResponseStream);
// Check upload result
if Client.ResponseStatusCode = 200 then
begin
Writeln('Upload successful!');
Writeln('Server response status: ', Client.ResponseStatusCode);
Writeln('Response content type: ', Client.GetHeader(Client.ResponseHeaders, 'Content-Type'));
// Show part of the response
Writeln('Server response (first 200 chars):');
Writeln(Copy(ResponseStream.DataString, 1, 200));
end
else
begin
Writeln('Upload failed with status: ', Client.ResponseStatusCode);
Writeln('Response: ', ResponseStream.DataString);
end;
// Upload with additional form fields
Writeln('=== File Upload with Additional Fields ===');
ResponseStream.Clear;
// Add custom headers for the upload
Client.AddHeader('X-Upload-Purpose', 'documentation-example');
// You can also upload to services that expect additional form data
// by using FileFormPost combined with other form fields
finally
ResponseStream.Free;
Client.Free;
// Clean up test file
if FileExists(TestFileName) then
DeleteFile(TestFileName);
end;
end.
Important Notes:
- The file must exist and be readable for the upload to succeed.
- The form field name should match what the server expects.
- The method automatically sets Content-Type to multipart/form-data
- Large files are streamed efficiently without loading entirely into memory
- The server response is written to the provided response stream
An experiment, built from development snapshots. Not the official Free Pascal or Lazarus documentation.
