delphi 将文件作为字节数组发送到 Rest 服务

delphi Send a file as byte array to a Rest service

我正在使用 Delphi 10.1 Berlin

我想使用 TRestRequest 将图像数据作为 TBytes 发送到 Rest 服务,但我找不到将 TBytes 传递到 TRestRequest.AddBody() 的方法方法,或任何其他方法。

POST http://myserver:1111//Openxxx/RecxxxLxxxPxxxx HTTP/1.1
Content-Type: text/json
Host: myserver:1111
Content-Length: 28892
Expect: 100-continue
Connection: Keep-Alive

[255,216,255,224,0,16,74,70,73,70,0,1,1,0,0,1,0,1,0,0,255,219,0,132,0,9,
...
...
...
130,130,252,168,127,164,63,164,41,109,204,245,62,106,51,135,12,146,63,255,217]

TRESTRequest.AddBody() has an overload that accepts a TStream as input. You can wrap your TBytes into a TStream using the TBytesStream class.

procedure TForm1.Button1Click(Sender: TObject);
var
  ABytes: TBytes;
  AStream: TBytesStream;
begin
  ABytes := ...;
  try
    AStream := TBytesStream.Create(ABytes);
    RESTRequest1.AddBody(AStream, ctIMAGE_JPEG); 
    RESTRequest1.Execute;
  finally
    AStream.Free;
  end;
end;

或者,使用 TRESTRequestParameterList.AddItem 代替,它有 TBytes:

的重载
procedure TForm1.Button1Click(Sender: TObject);
var
  ABytes: TBytes;
begin
  ABytes := ...
  RESTRequest1.Params.AddItem('body', ABytes, pkGETorPOST, [poDoNotEncode], ctIMAGE_JPEG);
  RESTRequest1.Execute;
end;

话虽如此,我发现 TRESTClient 过于复杂并且 buggy/limiting。很多时候,Indy 的 TIdHTTP 更容易使用,例如:

procedure TForm1.Button1Click(Sender: TObject);
var
  ABytes: TBytes;
  AStream: TBytesStream;
begin
  ABytes := ...;
  try
    AStream := TBytesStream.Create(ABytes);
    IdHTTP1.Request.ContentType := 'image/jpeg';
    IdHTTP1.Post('http://myserver:1111//Openxxx/RecxxxLxxxPxxxx', AStream);
  finally
    AStream.Free;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
  IdHTTP1.Request.ContentType := 'image/jpeg';
  IdHTTP1.Post('http://myserver:1111//Openxxx/RecxxxLxxxPxxxx', 'image.jpg');
end;

我已经解决了如下问题:

function BytesToStr(abytes: tbytes): string;
var
  abyte: byte;
begin
   for abyte in abytes do
   begin
      Result := result + IntToStr(abyte) + ',';
   end;
   Result := '[' + Copy(Result, 1, Length(Result) - 1) + ']';
end;

procedure TForm1.Button1Click(Sender: TObject);
var
   ABytes: TBytes;
begin
   ABytes := TFile.ReadAllBytes('images.jpg');
   RESTRequest1.Params.AddItem('body', BytesToStr(ABytes), pkREQUESTBODY, [], ctAPPLICATION_JSON);
   RESTRequest1.Execute;
end;