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

时间:2017-03-15 14:04:31

标签: arrays rest delphi delphi-10.1-berlin

我正在使用Delphi 10.1 Berlin

我想使用TBytes将图像数据作为TRestRequest发送到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]

2 个答案:

答案 0 :(得分:4)

TRESTRequest.AddBody()有一个重载,接受typecast作为输入。您可以使用TBytesStream类将TStream打包到TBytes

TStream

或者,请使用TRESTRequestParameterList.AddItem代替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;

TBytes

话虽这么说,我发现procedure TForm1.Button1Click(Sender: TObject); var ABytes: TBytes; begin ABytes := ... RESTRequest1.Params.AddItem('body', ABytes, pkGETorPOST, [poDoNotEncode], ctIMAGE_JPEG); RESTRequest1.Execute; end; 过于复杂和错误/限制。更多的时候,Indy的TRESTClient更容易使用,例如:

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;

答案 1 :(得分:0)

我已经解决了我的问题,如下所示:

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;