【问题标题】:Base64 is breaking lines when encoding in Delphi [duplicate]在Delphi中编码时Base64断线[重复]
【发布时间】:2019-08-05 17:22:46
【问题描述】:

我正在使用 delphi 中的以下代码 sn-p 将图像编码为 Base64

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;

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

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

你可以看到红色的是字符串。第一个换行后,json被打乱,显示为蓝色,表示json响应有错误。

问题

所以,问题在于,当编码为Base64 时,它会在字符串中添加换行符,而Json 不支持这一点。

我的猜测

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

我遍历了TStringList 中的所有Strings,并将数据添加到TStringBuilder 中。毕竟,我在Json 中添加了TStringBuilder。看看我的代码。

...
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;

如您所见,JSON 现在很好。

问题

  1. 循环遍历所有项目对我来说似乎是一个不好的解决方案,它可以正常工作吗? (它在 localhost 上 344 毫秒内得到响应)
  2. 有更好的解决方案吗?

【问题讨论】:

    标签: json delphi


    【解决方案1】:

    创建您自己的实例并在Create 中将CharsPerLine 参数指定为0,而不是方便的实例TNetEncoding.Base64

      encoding := TBase64Encoding.Create(0);
      try
        encosing.Encode(inStream, outStream);
      finally
        encoding.Free;
      end;
    

    【讨论】:

    • 这个问题的骗子不少.....
    猜你喜欢
    • 2013-02-03
    • 2015-04-18
    • 2015-07-14
    • 1970-01-01
    • 2020-04-03
    • 2019-06-21
    • 2019-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多