How do I receive a file using TRESTClient/TRESTResponse? Currently only able to receive text.
RESTResponse1.Content
How do I receive a file using TRESTClient/TRESTResponse? Currently only able to receive text.
RESTResponse1.Content
There is a class in namespace REST.Client
that can download binary data:
REST.Client.TDownloadURL.DownloadRawBytes
uses REST.Client, IpPeerClient;
<...>
bStream := TMemoryStream.Create;
TDownloadURL.DownloadRawBytes(url, bStream);
<...>
You should also use an implementation unit IpPeerClient
.
Try this:
A simple PHP Web Service for get a JPG file:
<?php
$path = 'c:\1.jpg'; // file path on server
$data = file_get_contents($path);
$base64 = base64_encode($data);
$json = array("status" => 1, "info" => $base64);
header('Content-type: application/json');
echo json_encode($json,JSON_UNESCAPED_UNICODE);
Delphi code for saving JPG file from server:
procedure TForm1.btn1Click(Sender: TObject);
var
strResponeContnt : string;
oJSON: TJSONObject;
aJSON: TJSONArray;
strImageJSON : string;
varMemoryString : TMemoryStream;
begin
restClient1.BaseURL := 'http://test/getfile.php';
restRequest1.Client := restClient1;
restRequest1.Response := restResponse1;
restRequest1.Execute;
strResponeContnt := restResponse1.Content;
oJSON := TJSONObject.ParseJSONValue(TEncoding.ASCII.GetBytes(strResponeContnt),0) as TJSONObject;
aJSON := TJSONArray(oJSON.Get('info').JsonValue);
strImageJSON := deQuotedString(oJSON.Pairs[1].JsonValue.ToString) ;
varMemoryString := TMemoryStream.Create;
try
IdDecoderMIME1.DecodeStream(strImageJSON, varMemoryString);
varMemoryString.Position := 0;
varMemoryString.SaveToFile('C:\3.jpg');
finally
varMemoryString.Free;
end;
end;
deQuotedString
function:
function TForm1.deQuotedString(Value:String):String;
var
strtmp : string;
begin
strtmp := Value;
delete(strtmp,1,1);
delete(strtmp,Length(strtmp),1);
Result := strtmp;
end;
Class variable declaration:
restClient1: TRESTClient;
restRequest1: TRESTRequest;
restResponse1: TRESTResponse;
IdDecoderMIME1: TIdDecoderMIME;
JSON
uses Unit:
System.JSON
After all you can download file Directly using other Delphi web controls such as INDY and save it.
TRestResponse is not good for binary data.
Use idHTTP.
mem := TMemoryStream.Create;
idHttp1.Get('http://localhost/index.php', mem);
//do something
mem.free;