在Delphi中进行编码时,Base64出现断行

Soo*_*tos 1 delphi json

我正在将图像编码为Base64在delphi中使用以下代码段。

procedure TWM.WMactArquivosAction(Sender: TObject; Request: TWebRequest;
  Response: TWebResponse; var Handled: Boolean);
var
  ImagePath: string;
  JsonObject: TJSONObject;
  inStream, outStream: TStream;
  StrList: TStringList;
begin
  inStream := TFileStream.Create(ImagePath, fmOpenRead);
  try
    outStream := TFileStream.Create('final_file', fmCreate);
    JsonObject := TJSONObject.Create;
    try
      TNetEncoding.Base64.Encode(inStream, outStream);
      outStream.Position := 0;
      StrList := TStringList.Create;
      StrList.LoadFromStream(outStream);

      JsonObject.AddPair('file', StrList.Text);
    finally
      Response.Content := JsonObject.ToString;
      outStream.Free;
      JsonObject.DisposeOf;
    end;
  finally
    inStream.Free;
  end;
end;
Run Code Online (Sandbox Code Playgroud)

工作正常,文件被转换为Base64并添加到JsonObject

问题是,当JsonObject从网络服务器检索此消息时,我得到了格式错误的json,因为base64字符串中有换行符

格式错误的json

您会看到红色的是字符串。第一行中断后,json受到干扰,并以蓝色显示,这意味着json响应中有错误。

问题

因此,问题在于,在对其进行编码时Base64,在字符串上添加了换行符,而则不支持Json

我猜

我有一个猜测,它确实有效,但是我不确定这是最佳解决方案。

我遍历了所有StringsTStringList然后将数据添加到中TStringBuilder。毕竟,我将添加TStringBuilderJson。看我的代码。

...
var
  ...
  StrBuilder: TStringBuilder;
begin
  ...
    try
      ...
      StrList.LoadFromStream(outStream);

      // New
      StrBuilder := TStringBuilder.Create;
      for I := 0 to StrList.Count - 1 do
        StrBuilder.Append(StrList.Strings[I]);

      JsonObject.AddPair('file', StrBuilder.ToString);
    finally
      Response.Content := JsonObject.ToString;
      ...
    end;
  ...
end;
Run Code Online (Sandbox Code Playgroud)

json格式正确

如您所见,JSON现在很好。

问题

  1. 循环浏览所有项目对我来说似乎是一个不好的解决方案,它将正常工作吗?(它在344ms的本地主机上得到响应)
  2. 有更好的解决方案吗?

Uwe*_*abe 5

代替便利实例,TNetEncoding.Base64创建您自己的实例,并使用0 指定CharsPerLine参数Create

  encoding := TBase64Encoding.Create(0);
  try
    encosing.Encode(inStream, outStream);
  finally
    encoding.Free;
  end;
Run Code Online (Sandbox Code Playgroud)