A new cross-language example for HTTP and REST is now available on GitHub.

Description

Single file upload example using Delphi client and Java server code and HTTP multipart/form-data

Requirements

  • Delphi 2009 or newer
  • Indy 10.6.2
  • Java JDK 8 or newer
  • Apache Maven
  • WildFly application server

Client

[sourcecode lang=”Delphi”]
program IndyPostFormData;

{$APPTYPE CONSOLE}

uses
IdHTTP, IdMultipartFormData, SysUtils;

const
URL = ‘http://localhost:8080/indy-post-formdata-1.0-SNAPSHOT/webresources/generic/pdf’;

var
Indy: TIdHTTP;
Params: TIdMultiPartFormDataStream;
Response: string;

begin
Indy := TIdHTTP.Create;
Params := TIdMultiPartFormDataStream.Create;
try
try
Params.AddFile(‘file’, ‘client.pdf’);
Response := Indy.Post(URL, Params);
WriteLn(Response);
except
on E:Exception do
Writeln(E.Classname, ‘: ‘, E.Message);
end;
finally
Params.Free;
Indy.Free;
end;
ReadLn;
end.
[/sourcecode] 

Server (main REST method)

[sourcecode lang=”Java”]
@POST
@Path(“/pdf”)
@Consumes({MediaType.MULTIPART_FORM_DATA})
public Response upload(MultipartFormDataInput input) {
String UPLOAD_PATH = “c:/tmp/”;
try {
InputStream fileInputStream = input.getFormDataPart(“file”, InputStream.class, null);
String fileName = “test.pdf”;

int read;
byte[] bytes = new byte[1024];

try (OutputStream out = new FileOutputStream(new File(UPLOAD_PATH + fileName))) {
while ((read = fileInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
}
} catch (IOException e) {
throw new WebApplicationException(“Error while uploading file. Please try again”);
}
return Response.ok(“Data uploaded successfully”).build();
}
[/sourcecode] 

Full source code

https://github.com/michaelJustin/indy-post-formdata


Discover more from Habarisoft Blog

Subscribe to get the latest posts sent to your email.

One thought on “Single file upload example using Indy TidHTTP and multipart/form-data

Leave a Reply

Your email address will not be published. Required fields are marked *