我正在将图像编码为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响应中有错误。
问题
因此,问题在于,在对其进行编码时Base64,在字符串上添加了换行符,而则不支持Json。
我猜
我有一个猜测,它确实有效,但是我不确定这是最佳解决方案。
我遍历了所有Strings,TStringList然后将数据添加到中TStringBuilder。毕竟,我将添加TStringBuilder到Json。看我的代码。
...
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现在很好。
问题
代替便利实例,TNetEncoding.Base64创建您自己的实例,并使用0 指定CharsPerLine参数Create。
encoding := TBase64Encoding.Create(0);
try
encosing.Encode(inStream, outStream);
finally
encoding.Free;
end;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
72 次 |
| 最近记录: |